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!
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!
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.
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;