Get elements by XPath – JavaScript

I was trying to do a querySelector by text, trying to find elements with certain text content of an element.

It turns out you can do that with XPath without much effort. With any XPath expression you can think of.

function getElementsByXPath(xpath, parent) { let results = []; let query = document.evaluate(xpath, parent || document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); for (let i = 0, length = query.snapshotLength; i < length; ++i) { results.push(query.snapshotItem(i)); } return results; }

Query the elements

In my particular use caes, the HTML looks like this:

<div> <ul> <li> Item <span>ADDED</span> </li> <li> Item <span>REMOVED</span> </li> </ul> </div>

Use your XPath expressions to query the elements by certain text:

const $elements = getElementsByXPath("//span[contains(., 'ADDED')]");

Loop through them

Use forEach to loop through the array:

$elements.forEach(($element) => { // Do something })



Leave a Reply

Add <code> Some Code </code> by using this tags.