4

I'm new to DOM querying and I'm wondering if it is possible to query DOM elements directly by Xpath in a similar way to the below-mentioned code?

document.getElementById("searchInput");

Thanks!

user3648426
  • 227
  • 1
  • 4
  • 13
  • 1
    Yes, XPath can do that. `//*[@id='searchInput']` – Marc B Jun 17 '14 at 17:40
  • Thanks, so I would just pass the Xpath as a parameter to the getElementById method? – user3648426 Jun 17 '14 at 17:42
  • @user3648426 no. thats the equivalent xpath. – Daniel A. White Jun 17 '14 at 17:42
  • no. gEBI has nothing to do with xpath. xpath is a general purpose dom tree querying tool. gEBI is a very very specific search, and *may* use xpath internally, but probably doesn't for efficiency. – Marc B Jun 17 '14 at 17:43
  • Does this answer your question? [Is there a way to get element by XPath using JavaScript in Selenium WebDriver?](https://stackoverflow.com/questions/10596417/is-there-a-way-to-get-element-by-xpath-using-javascript-in-selenium-webdriver) – Asalan Dec 10 '22 at 23:55

2 Answers2

8

The equivalent statement using only XPath would be

xPathResult = document.evaluate('//*[@id="searchInput"]', document);
if(xPathResult){
     element = xPathResult.iterateNext();
}

Have a look at the Intro to XPath in the browser on MDN for some more examples and usages.

OozeMeister
  • 4,638
  • 1
  • 23
  • 31
1

If you're looking for one or the first element behind your XPath, you can use this one liner:

const yourstring = "/html/body/div[1]/div[1]/div/div[3]/div[1]/h3";
const element = document.evaluate(yourstring, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;
Neithan Max
  • 11,004
  • 5
  • 40
  • 58