How can I get all element's immediate children with css selectors using selenium?

SeleniumAutomation TestingTesting Tools

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. To get all the immediate children we have to specify * symbol after parent node in the css expression. So the customized css should be parent > *.

So for a <ul class="toc chapter">, the css for immediate children shall be ul.toc.chapters >*.


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class ImdtChildrenCss{
   public static void main(String[] args) {
      System.setProperty("", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "";
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify and store immediate children of parent in css
      List<WebElement> l = driver.findElements(By.cssSelector("ul.toc.chapters" + ">*"));
      // Iterate list and get the children
      for (int i =0; i< l.size(); i++) {


Published on 28-Aug-2020 16:26:39