Anton Tarasenko
Anton Tarasenko

Reputation: 8475

Finding all elements containing a string with XPath in JavaScript

I'm trying to get all elements containing a string:

function getElementsByText( text, ctx) {
  return document.evaluate(
      "//*[.='"+text+"']", 
      ctx || document,
      null,
      XPathResult.ORDERED_NODE_ITERATOR_TYPE,
      null
    ).iterateNext();
}

var searchString = "Name";
var parents = getElementsByText(searchString);

for (var i = 0; i < parents.length; i++) {
  parents[i].style.opacity = .2;
};

The docs say evaluate with ORDERED_NODE_ITERATOR_TYPE returns "all the nodes matching the expression". But getElementsByText returns only the first occurrence.

This code doesn't work because parents is not iterable.

How can I get all the elements?

Upvotes: 2

Views: 1761

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

If you call the evaluate method you will get an https://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#XPathResult on which you need to call iterateNext as long as you want the next node of the selected nodeset. If you want to have an array then do e.g.

function getElementsByText( text, ctx) {
  var results = [];
  var xpathResult = document.evaluate(
      "//*[.='"+text+"']", 
      ctx || document,
      null,
      XPathResult.ORDERED_NODE_ITERATOR_TYPE,
      null
    );
   var node;
   while ((node = xpathResult.iterateNext()) != null) {
     results.push(node);
   }
   return results;
}

Upvotes: 3

Related Questions