Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  86] [ 1]  / answers: 1 / hits: 48913  / 8 Years ago, wed, march 30, 2016, 12:00:00

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
);

More From » xpath

 Answers
17

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

[#62760] Monday, March 28, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cody

Total Points: 679
Total Questions: 111
Total Answers: 111

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;