Get Element by XPath using JavaScript - Examples

avatar

Borislav Hadzhiev

Mon Jan 03 20222 min read

banner

Photo by freestocks

Get Element by XPath using JavaScript - Examples #

Use the document.evaluate() method to get an element by XPath. The method returns an XPathResult based on the provided XPath expression and the supplied parameters.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div> <p>Hello world</p> </div> <div> <p>Apple, Banana, Kiwi</p> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript.

index.js
// ✅ Get specific `p` element const firstP = document.evaluate( '/html/body/div[2]/p', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null, ).singleNodeValue; console.log(firstP); // 👉️ p console.log(firstP.textContent); // 👉️ "Apple, Banana, Kiwi" // ----------------------- // ✅ Get all P elements const allParagraphs = document.evaluate( '/html/body//p', document, null, XPathResult.ANY_TYPE, null, ); console.log(allParagraphs); let currentParagraph = allParagraphs.iterateNext(); while (currentParagraph) { console.log(currentParagraph.textContent); currentParagraph = allParagraphs.iterateNext(); }

We used the document.evaluate method to get an XPathResult based on an XPath expression.

The first example shows how to get a single node, whereas the second gets a collection of nodes and iterates over it.

The document.evaluate method takes the following parameters:

  1. xpathExpression - the XPath to be evaluated
  2. contextNode - the context node for the query (usually document)
  3. namespaceResolver - should be null when working with HTML documents
  4. resultType - the type of XPathResult to return.
  5. result - should be null

Notice that in the first example we accessed the singleNodeValue property on the XPathResult object.

index.js
// ✅ Get specific `p` element const firstP = document.evaluate( '/html/body/div[2]/p', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null, ).singleNodeValue; console.log(firstP); // 👉️ p console.log(firstP.textContent); // 👉️ "Apple, Banana, Kiwi"
The singleNodeValue property returns the first found node that matched the XPath expression.

This will evaluate to null if the node set is empty.

Another thing to note in the example, is that we specified a result type of XPathResult.FIRST_ORDERED_NODE_TYPE.

If you look at the XPath Result types table, this result type returns any single node that matches the provided XPath expression.

In the second example we used an XPath expression to get all p elements in the document and iterated over the results.
index.js
// ✅ Get all P elements const allParagraphs = document.evaluate( '/html/body//p', document, null, XPathResult.ANY_TYPE, null, ); let currentParagraph = allParagraphs.iterateNext(); while (currentParagraph) { // 👇️ "Hello world", "Apple, Banana, Kiwi" console.log(currentParagraph.textContent); currentParagraph = allParagraphs.iterateNext(); }

This time we set XPAthResult.ANY_TYPE as the result type, which returns whatever type results from the provided XPath expression.

The returned XPathResult object is a node-set of matches nodes that behave as an iterator.

We are able to access the individual nodes by using the iterateNext() method of the XPathResult object.

Once we have iterated over all of the nodes, the iterateNext() method will return null.

Note that modifying a node will invalidate the iterator. After modifying a node, attempting to iterate over the results generates an error.
Use the search field on my Home Page to filter through my more than 1,000 articles.