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.tsx263 chars6 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