Is there a relative CSS locator for Selenium?

Suppose I'm looking for some div elements in a #myPage element . My goal is to use CSS selectors and limit the search to only descendants of #myPage .

Using Selenium XPath locators, I can write something like this:

WebElement page = driver.findElement(new By.ById("myPage"));
....
List<WebElement> item = page.findElements(new By.ByXPath(".//div"));

However, an attempt to use CSS gives all the divs in the documents, not just the descendants of #myPage :

WebElement page = driver.findElement(new By.ById("myPage"));
....
List<WebElement> item = page.findElements(new By.ByCssSelector("div"));

The big difference is the prefix .//that makes the XPath expression relative. I could not find a similar property in CSS syntax, and I wonder if this is possible.

PS
I know that I can use an expression #myPage > div, but then I combine the page search operation with the search for my descendants, which is not always desirable.

+2
source share
1 answer

This functionality does not exist yet. There, a similar function is offered in the Selectors API level 2 API for the DOM and is encoded at level 4 of the choice as a relative selector , but I do not know if Selenium will ever implement such a function.

If you need to do a relative search, XPath is your only option.

+2
source

All Articles