How to use document.evaluate() and XPath to get a list of elements?
35,520
Solution 1
I found the following solution in the book I am currently reading. It says that the code is from the Prototype library.
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;
}
Use it like this:
let items = getElementsByXPath("//*"); // return all elements on the page
Solution 2
From the documentation
var iterator = document.evaluate('//phoneNumber', documentNode, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null );
try {
var thisNode = iterator.iterateNext();
while (thisNode) {
alert( thisNode.textContent );
thisNode = iterator.iterateNext();
}
}
catch (e) {
dump( 'Error: Document tree modified during iteration ' + e );
}
Solution 3
Try this:
function getListOfElementsByXPath(xpath) {
var result = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null);
return result;
}
Then call it:
var results = getListOfElementsByXPath("//YOUR_XPATH");
while (node = results.iterateNext()) {
console.log(node);
}
Author by
Abhishek Tripathi
Updated on March 19, 2021Comments
-
Abhishek Tripathi over 3 years
I'm using the
document.evaluate()
JavaScript method to get an element pointed to by an XPath expression:var element = document.evaluate( path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
But how do I get a list of elements in case the XPath expression points to more than one element on the page?
I tried the following code, but it is not working:
var element = document.evaluate( path, document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
-
CS QGB over 4 yearsFailed to read the 'snapshotLength' property from 'XPathResult': The result type is not a snapshot.
-
Kamafeather almost 4 yearsMmh.. first time I am trying to use it. Looks like i am getting the same "result type is not a snapshot" in any case, whatever is the document, the browser or the query (a simple one:
//div
).resultType
is always 4 and unable to get the snapshot. -
Kamafeather almost 4 yearsOk, I see (from Community Ans, down below). The result is an iterator.