Reputation: 473
Is there any way to do something like:
webElement.findElements(By.cssSelector("> li");
I'm trying to get the direct children of an WebElement object.
I know about the css selector "parent > children" and it works as expected, but my case is different.
For example:
<ul class="x">
<li>
<ul>
<li>
</li>
</ul>
</li>
<li>
</li>
</ul>
List<WebElement> webElements = driver.findElements(By.cssSelector("ul.x > li"));
returns only the direct sub-children of ul tag. The size of the List is 2. But I have the next use case:
WebElement webElement = driver.findElement(By.cssSelector("ul.x"));
webElement.findElements(By.cssSelector("li");
The problem here is that this code returns all 'li' web elements and not only the direct children. The size of the List is 3 this time.
I tried this:
webElement.findElements(By.cssSelector("> li");
but this throws an error
org.openqa.selenium.InvalidSelectorException: invalid selector: An invalid or illegal selector was specified
Upvotes: 7
Views: 2843
Reputation: 12255
You can use xpath:
WebElement webElement = driver.findElement(By.cssSelector("ul.x"));
webElement.findElements(By.xpath("./li");
Upvotes: 7