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; }
Code language: JavaScript (javascript)

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>
Code language: HTML, XML (xml)

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

const $elements = getElementsByXPath("//span[contains(., 'ADDED')]");
Code language: PHP (php)

Loop through them

Use forEach to loop through the array:

$elements.forEach(($element) => { // Do something })
Code language: PHP (php)



Leave a Reply

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