User Tools

Site Tools


docu:csheet:code:js:element_by_xpath

Get an element on the HTML document by XPath


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

— 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 documented: https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate

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]") );
 
<div>foo</div>

Source: https://stackoverflow.com/questions/10596417/is-there-a-way-to-get-element-by-xpath-using-javascript-in-selenium-webdriver

docu/csheet/code/js/element_by_xpath.txt · Last modified: 2020/06/03 12:27 by admin