Is there a way to get element by XPath using JavaScript in Selenium WebDriver?


Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

I am looking for something like:

I need to get the innerHTML of elements using JS (to use that in Selenium WebDriver/Java, since WebDriver can’t find it itself), but how?
I could use ID attribute, but not all elements have ID attribute.
I am using jsoup to get it done in Java. That works for my needs.


Solution 1:

You can use document.evaluate:

Evaluates an XPath expression string and returns a result of the
specified type if possible.

It is w3-standardized and whole documentend:

function getElementByXpath(path) {
  return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

console.log( getElementByXpath("//html[1]/body[1]/div[1]") );

There’s also a great introduction on mozilla developer network:

Alternative version, using XPathEvaluator:

function getElementByXPath(xpath) {
  return new XPathEvaluator()
    .evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)

console.log( getElementByXPath("//html[1]/body[1]/div[1]") );

Solution 2:

In Chrome Dev Tools you can run the following:

$x("some xpath")

Solution 3:

For something like $x from chrome command line api (to select multiple elements) try:

var xpath = function(xpathToExecute){
  var result = [];
  var nodesSnapshot = document.evaluate(xpathToExecute, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
  for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ ){
    result.push( nodesSnapshot.snapshotItem(i) );
  return result;

This MDN overview helped:

Solution 4:

You can use javascript’s document.evaluate to run an XPath expression on the DOM. I think it’s supported in one way or another in browsers back to IE 6.


IE supports selectNodes instead.


Solution 5:

Assuming your objective is to develop and test your xpath queries for screen maps. Then either use Chrome’s developer tools. This allows you to run the xpath query to show the matches. Or in Firefox >9 you can do the same thing with the Web Developer Tools console. In earlier version use x-path-finder or Firebug.

Solution 6:

public class JSElementLocator {

    public void locateElement() throws InterruptedException{
        WebDriver driver = WebDriverProducerFactory.getWebDriver("firefox");


        WebElement searchbox = null;

        searchbox = (WebElement) (((JavascriptExecutor) driver).executeScript("return document.getElementById('lst-ib');", searchbox));

Make sure you are using the right locator for it.