user3648426
user3648426

Reputation: 251

DOM find element by Xpath

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!

Upvotes: 5

Views: 15701

Answers (2)

Neithan Max
Neithan Max

Reputation: 11806

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;

Upvotes: 1

OozeMeister
OozeMeister

Reputation: 4869

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.

Upvotes: 9

Related Questions