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)

Enjoy!

Comments

  1. Nevermind I am dumb. Thanks for the article! (I was misunderstanding Xpath for my use case — needed //div//a not /div//a)

  2. Sorry, it does match if you don’t use the text selector, but it wont match more than one level deep for me. Ie the XPath expression ‘//a’ will work, but neither ‘/div//a’ nor ‘/*[@class=’main’]//a’ works

Leave a Reply

Your email address will not be published. Required fields are marked *