How To Get Element By Xpath In Javascript

When working with web pages, you may encounter situations where you need to get elements from the DOM using XPath. XPath (XML Path Language) is a powerful query language that allows you to navigate through an XML document. It is also useful when working with HTML since most web browsers can parse HTML using an XML parser.

In this blog post, we’ll explore how you can get elements by XPath in JavaScript using the document.evaluate() method.

Using document.evaluate() method

The document.evaluate() method is a built-in JavaScript function that allows you to evaluate an XPath expression within a specified context and return the result as an XPathResult object. Here’s the syntax of this method:

document.evaluate(xpathExpression, contextNode, namespaceResolver, resultType, result);

Let’s break down the parameters of this method:

  • xpathExpression: A string representing the XPath expression to be evaluated.
  • contextNode: The node within the document that acts as the context for the XPath expression. Normally, you’d use document as the context node.
  • namespaceResolver: A function that resolves namespaces within the XPath expression. This is usually set to null when working with HTML documents.
  • resultType: The desired result type, specified using the constants of the XPathResult object. Most commonly, you’ll use XPathResult.FIRST_ORDERED_NODE_TYPE for a single node, or XPathResult.ORDERED_NODE_ITERATOR_TYPE for multiple nodes.
  • result: An existing XPathResult object that you’d like to reuse, or null if you’d like a new one.

Example: Get a single element by XPath

Let’s say we have the following HTML snippet:

<div class="container">
    <p class="message">Hello, World!</p>
    <p class="message">Welcome to XPath in JavaScript!</p>
</div>

We want to get the first paragraph with the class “message”. Here’s how we can achieve this using the document.evaluate() method:

// Define the XPath expression
const xpathExpression = '//p[@class="message"]';

// Evaluate the expression and get the first matching node
const result = document.evaluate(xpathExpression, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

// Get the first matching node as an HTMLElement
const firstMessageElement = result.singleNodeValue;

// Log the inner text of the element
console.log(firstMessageElement.innerText);

This code will output:

Hello, World!

Example: Get multiple elements by XPath

Now, let’s say we want to get all the paragraphs with the class “message”. Here’s how we can do this:

// Define the XPath expression
const xpathExpression = '//p[@class="message"]';

// Evaluate the expression and get an iterator with the matching nodes
const result = document.evaluate(xpathExpression, document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);

// Iterate through the matching nodes
let messageElement;
while ((messageElement = result.iterateNext())) {
    // Log the inner text of each element
    console.log(messageElement.innerText);
}

This code will output:

Hello, World!
Welcome to XPath in JavaScript!

Conclusion

In this blog post, we’ve seen how to get elements by XPath in JavaScript using the document.evaluate() method. This powerful method allows you to navigate the DOM using XPath expressions, making it a useful tool in your web development toolkit.