WebElement body = browser.findElement(By.xpath("//body")); body.findElement(By.xpath("")); // I want to get all child elements // inside body, but nothing deeper.
Example document.
<html> <body> <div> </div> <span> <table> </table> </span> </body> </html>
Expected result is div
and span
. I have no controll over the documents and they vary greatly.
Mastering XPath and CSS Selector for Selenium We can get all element's immediate children with css selectors. We have to use findElements() method to get immediate children. This method will return a list of elements matching css selector. In a css selector if we need to traverse from parent to child we use > symbol.
The child combinator ( > ) is placed between two CSS selectors. It matches only those elements matched by the second selector that are the direct children of elements matched by the first. Elements matched by the second selector must be the immediate children of the elements matched by the first selector.
("*")
gives all the child elements of the context node. So use:
body.findElement(By.xpath("*"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With