Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use document.evaluate() and XPath to get a list of elements?

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 ); 
like image 298
Abhishek Tripathi Avatar asked Mar 30 '16 08:03

Abhishek Tripathi


People also ask

How do I get XPath elements?

We can find an element using the xpath locator with Selenium webdriver. To identify the element with xpath, the expression should be //tagname[@attribute='value']. To identify the element with xpath, the expression should be //tagname[@class='value']. There can be two types of xpath – relative and absolute.

What is XPath evaluate?

XPath provides access to the XPath evaluation environment and expressions. Evaluation of XPath Expressions. context. If a request is made to evaluate the expression in the absence of a context item, an empty document node will be used for the context.

How are XPath expressions evaluated?

The Evaluate method takes an XPath expression, evaluates it, and returns a typed result of Boolean (Boolean), Number (Double), String (String), or Node Set (XPathNodeIterator). For example, the Evaluate method could be used in a mathematical method.


Video Answer


2 Answers

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 
like image 83
Krisztián Balla Avatar answered Sep 24 '22 12:09

Krisztián Balla


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 ); } 
like image 45
kernowcode Avatar answered Sep 26 '22 12:09

kernowcode