Skip to main content
Notice removed Draw attention by alecxe
Bounty Ended with Sᴀᴍ Onᴇᴌᴀ's answer chosen by alecxe

Evaluating an XPath with document.evaluate() to get an array of nodes

Tweeted twitter.com/StackCodeReview/status/884457546311884800
Notice added Draw attention by alecxe
Bounty Started worth 50 reputation by alecxe
Source Link
alecxe
  • 17.5k
  • 8
  • 52
  • 93

Evaluating an XPath with document.evaluate()

The Problem Statement:

Filter all nodes with an existing attribute that starts with a specific string (temp for example purposes). Print an array of node string representations as a result.

The Code:

var result = document.evaluate("//*[@*[starts-with(name(), 'temp')]]", document, null, XPathResult.ANY_TYPE, null); var node = result.iterateNext(); var nodes = []; while (node) { nodes.push(node); node = result.iterateNext(); } console.log(nodes);
<div temp-callback="1" temp-post-callback="4"></div> <div temp-callback="2"></div> <div></div> <div temp-callback="8" temp-post-callback="7"></div>

The code is a bit bulky for such a straightforward problem. Is there a simpler and a more concise way to get an array of nodes from a document.evaluate() result?