user3364652 user3364652 - 9 months ago 44
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("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


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

Answer Source

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.