select by xpath in javascript

To select an element in the DOM using xpath in JavaScript, you can use the document.evaluate() method which evaluates an XPath expression within a given context node and returns an ordered node iterator.

Here's an example of how to use document.evaluate() to select an element by xpath:

index.tsx
// select the first element with class 'my-class'
var element = document.evaluate("//div[contains(@class, 'my-class')]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

// do something with the element
console.log(element.innerHTML);
263 chars
6 lines

In this example, we're selecting the first div element that contains the class my-class. The document argument specifies the context node (the root node of the document). null specifies the namespace resolver (not used in this example). XPathResult.FIRST_ORDERED_NODE_TYPE specifies the type of result we want (in this case, the first node that matches the XPath expression). Finally, null specifies a result object (not used in this example).

The singleNodeValue property of the result object contains the selected element.

gistlibby LogSnag