user3364652 user3364652 - 24 days ago 7
Java Question

Why I must search explicitly relative elements in Selenium by xpath?

I'm trying to look for elements by xpath with Selenium's WebDriver:

WebElement element1 = driver.findElement(By.id("someID"));
List<WebElement> xPathElements = element1.findElements((By.xpath("//span[@class='someClass']")));


With this code, I'm getting all the elements with class='someClass' in the DOM.

Only when I add "." at the beginning of the xpath string I get all the elements with class='someClass' that are under
element1


element1.findElements((By.xpath(".//span[@class='someClass']")));


What's the sense here? I called
findElements
from
element1
so by default it should search for elements that are under
element1
, Why I must add the "."?

Answer

It has got nothing to do with Selenium, it is the way xpath works.

If you have something like //elem xpath will located anywhere in the document. But if you want to search for an element relative to another element or rather a descendant then you have to use a '.' or a dot like .//elem.

Comments