2

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?

1

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.