How to select first child element in Selenium java

To select the first children of a given Selenium element, we can simply use the :first-child CSS selector.

Here is an example which will find the first child having div tag.

1WebElement childDiv = element.findElement(By.cssSelector("div:first-child"));

In case we want to get the list of immediate child elements, we have to use ./child::* as the xpath expression like this:

1List<WebElement> children = element.findElements(By.xpath("./child::*"));
2
3for (WebElement child: children) {
4        // processElement(child);
5}

References:


comments powered by Disqus