4

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

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, trying to use CSS yields all divs in documents, not only 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 couldn't find similar property in CSS syntax, and I wonder if it's even possible.

P.S.
I know I can use #myPage > div expression, but then I couple the page lookup operation with the lookup of its descendants, which is not always desirable.

2
  • i would try this: driver.findElements(By.cssSelector("#myPage div")) anyway, your first operation is looking for the page with the certain ID. and second operation - is looking for the elements on the page ('div' descedants). "#myPage div" cssSelector seems to unite your operations Commented Oct 21, 2012 at 9:57
  • Thank you for your response but coupling these operations is not always wanted. Commented Oct 21, 2012 at 19:55

1 Answer 1

5

This functionality doesn't exist yet. There's a similar feature being proposed in Selectors API level 2 for DOM, and codified in Selectors level 4 as relative selectors, but I don't know if Selenium will ever implement such a feature.

If you must perform a relative lookup, XPath is your only option for now.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.