get contents of xpath in javascript

To access the contents of an XPath expression in JavaScript, we first need to parse the HTML document into a DOM structure, and then evaluate the XPath expression to select the desired element(s).

Assuming we have an HTML document already loaded, we can parse it into a DOM structure like this:

index.tsx
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
93 chars
3 lines

where htmlString is the string representation of the HTML document.

Next, we can use the document.evaluate method to select the desired element(s) using an XPath expression. For example, to get the text contents of the first <h1> element in the document, we can do:

index.tsx
const xpathResult = doc.evaluate('//h1[1]', doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
const heading = xpathResult.singleNodeValue;
const text = heading.textContent;
178 chars
4 lines

In this example, we use the XPath expression //h1[1] to select the first <h1> element in the document, regardless of its position in the hierarchy. We then get the text contents of the element using the textContent property.

Note that the document.evaluate method returns an instance of XPathResult, which can contain a single node (as in this example), a node list, a boolean value, or a numeric value. The XPathResult.FIRST_ORDERED_NODE_TYPE constant tells the method to return only the first matching node.

gistlibby LogSnag