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 );
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.
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.
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.
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
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 ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With