How can I get all element's immediate children with css selectors using selenium?
23,758
You should specify a tag to start from... if you want "all element's immediate children", you would simply get all elements, which isn't really what you want.
To get "all immediate children of an element but not their children" for body
, use body > *
.
Or another example, to get all direct descendants of <div id='question'>
, use div#question > *
.
![Shiran](https://i.stack.imgur.com/gRpW0.jpg?s=256&g=1)
Author by
Shiran
Updated on November 24, 2020Comments
-
Shiran over 3 years
I already tried using the ">" syntax but selenium does not accept it, I know there is a way to get it using Xpath but our entire project is written using CSS selectors.
I am trying to store a list that will contain all immediate children of an element but not their children (descendants), when I use the "*" syntax I get all the element's descendants.
-
Shiran over 12 yearsThanks! that was helpful!!! We tried to use the > * in relativity to the webElement (like:
someWebElement.findElements(By.cssSelector(">*"))), instead of: webDriver.findElements(By.cssSelector(elementLocator + ">*").
-
Geert Bellemans over 8 yearsBe aware that this is an extremely inefficient selector! Css selectors are validated from right to left so by using the asterix (*, aka universal selector) at the end of the selector the browser will select all elements and then starts filtering further (in this case: only the elements that are direct children of the 'body' element). So for small pages this would not be an issue but in larger single page apps it can slow things down...