selenium: WebElement.FindElement(By.XPath) returns element not relative to parent but to the document

Meta -

OS: Windows 7 Selenium Version: 3.0.1.0 Browser: Chrome

When calling WebElement.FindElement(By.XPath(‘//element’) getting wrong results. the result is same as Driver.FindElement(By.XPath(‘//element’) - instead of the element inside that parent.

I have a workaround: WebElement.FindElement(By.XPath(‘.//element’) (add ‘.’) But I think this is unnecessary because I try to find element inside its parent

Page for example:

<html>
<body>
<div id="first">
    <button onclick="alert('first Btn clicked');">firstBtn</button>
</div>
<div id="second">
    <button onclick="alert('second Btn clicked');">secondBtn</button>
</div>
</body>
</html>

Code:

// wrongly clicks first button
Driver.FindElement(By.Id("second")).FindElement(By.XPath("//button")).Click();
// works correct
Driver.FindElement(By.Id("second")).FindElement(By.XPath(".//button")).Click();

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 3
  • Comments: 15 (3 by maintainers)

Most upvoted comments

the ‘//’ not always meant to say relative to document root / anywhere in the document as the selector ‘.//button’ means any descendant of current element. I’m writing locators for 3 years and never imagine that when I search for an element in context of another element than the search will be from the root. just because I had a bug in my test result then after debugging it I realize this. I’m sure that most of the people do not know about this behavior. I still think that like in any language when you query XML with XPath, and you search for nodes inside other nodes the result will be relative to node not the document

Thanks for sharing the answer (“.//”), this “bug” was killing me 😃

Please make this expected behavior more clear in the docs.

the ‘/’ in the beginning always means the document root. Read the XPath specification: https://www.w3.org/TR/xpath/#location-paths start from the sentence “There are two kinds of location path: relative location paths and absolute location paths.”

@barancev I’m sorry but I think that you didn’t understand the issue. You said that ‘/’ means document root I opened this issue about ‘//’ in the beginning ‘//’ can be anywhere in the doc but also can be any descendant (not only direct child)

See in the same link that you gave:

“chapter//para selects the para element descendants of the chapter element children of the context node”

Please read again

I believe this is working as expected.

In your first example, you are saying “//button”. You are telling it to start at the root (html node) and find the first button it finds, which is firstBtn. The second example states to search for the first button it finds from the current location by using the (.). This is the appropriate usage.

This is how xpath works and not a Selenium thing to fix if it were an issue.