The FindElement() method doesn't seem to work with an XPath locator, if called on an existing WebElement.

My code is this:

htmlDiv = _driver.FindElement(By.XPath("//h2[text()='" + onvNaam + "']/../.."));
htmlControl = htmlDiv.FindElement(By.XPath("//label[text()='Naam']/following-sibling::div[1]//select"));

The result of this code is that htmlControl contains the first matching element in the page, not the matching element in htmlDiv.

For other controls (with other By types) this seems to work.

Is the Xpath double slash superceding the scope of htmlDiv?


3 Answers 3


Ok, this isn't a bug. The XPath, when searching in the context of an element, must start with a dot. So this works:

htmlControl = htmlDiv.FindElement(By.XPath(".//label[text()='Naam']/following-sibling::div[1]//select"));

Do two simple steps:

First initialise webdriver element then try to find element using xpath, as explained below

WebDriver driver=new FirefoxDriver();
driver.find element(By.xpath("enter your xpath")).click();
  • Xpath is the best way to find an element followed by id, cssselector and name... Oct 29, 2014 at 12:27

According to Selenium best practices, XPath is locator of last preference.

Preferred selector order : id > name > css > xpath

Ask your web designers to add IDs or names to elements you need to interact with. Take them to the lunch and talk how IDs make your life easier. Bribe them is you have to.

  • Fully agree, but that doesn't mean the provided functionalities should have bugs. :) Also, I'm running into vaguely comparable issues with the CssSelector.
    – FDM
    Oct 17, 2014 at 13:31
  • 1
    Go and fix it - it is open source. Easy. Or switch to some proprietary tools which are known to have no bugs, ever. Oct 17, 2014 at 16:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.