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

Query the elements

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

      Item <span>ADDED</span>
      Item <span>REMOVED</span>
</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)



  1. I’m glad it worked out in the end Henry! ๐Ÿ™‚

  2. Henry says:

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

  3. Henry says:

    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

  4. Henry says:

    Why does this only work if you’re trying to match text?

Leave a Reply

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