Find Element By Xpath Javascript
Is there a way to get element by XPath using JavaScript in …
I am looking for something like:
getElementByXpath(//html[1]/body[1]/div[1]). innerHTML
I need to get the innerHTML of elements using JS (to use that in Selenium WebDriver/Java, since WebDriver can’t find it itself), but how?
I could use ID attribute, but not all elements have ID attribute.
[FIXED]
I am using jsoup to get it done in Java. That works for my needs.
asked May 15 ’12 at 7:55
2
In Chrome Dev Tools you can run the following:
$x(“some xpath”)
Matt71. 1k26 gold badges144 silver badges172 bronze badges
answered Dec 12 ’13 at 9:21
Dmitry SemenyukDmitry Semenyuk2, 6201 gold badge15 silver badges12 bronze badges
7
For something like $x from chrome command line api (to select multiple elements) try:
var xpath = function(xpathToExecute){
var result = [];
var nodesSnapshot = document. evaluate(xpathToExecute, document, null, XPathResult. ORDERED_NODE_SNAPSHOT_TYPE, null);
for ( var i=0; i < apshotLength; i++){
( apshotItem(i));}
return result;}
This MDN overview helped:
answered Jun 20 '14 at 16:55
JayJay3, 5492 gold badges20 silver badges24 bronze badges
To identify a WebElement using xpath and javascript you have to use the evaluate() method which evaluates an xpath expression and returns a result.
document. evaluate()
document. evaluate() returns an XPathResult based on an XPath expression and other given parameters.
The syntax is:
var xpathResult = document. evaluate(
xpathExpression,
contextNode,
namespaceResolver,
resultType,
result);
Where:
xpathExpression: The string representing the XPath to be evaluated.
contextNode: Specifies the context node for the query. Common practice is to pass document as the context node.
namespaceResolver: The function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. null is common for HTML documents or when no namespace prefixes are used.
resultType: An integer that corresponds to the type of result XPathResult to return using named constant properties, such as XPathResult. ANY_TYPE, of the XPathResult constructor, which correspond to integers from 0 to 9.
result: An existing XPathResult to use for the results. null is the most common and will create a new XPathResult
Demonstration
As an example the Search Box within the Google Home Page which can be identified uniquely using the xpath as //*[@name='q'] can also be identified using the google-chrome-devtools Console by the following command:
$x("//*[@name='q']")
Snapshot:
The same element can can also be identified using document. evaluate() and the xpath expression as follows:
document. evaluate("//*[@name='q']", document, null, RST_ORDERED_NODE_TYPE, null). singleNodeValue;
answered Jul 26 '20 at 23:37
DebanjanBDebanjanB125k30 gold badges187 silver badges238 bronze badges
public class JSElementLocator {
@Test
public void locateElement() throws InterruptedException{
WebDriver driver = tWebDriver("firefox");
(");
WebElement searchbox = null;
(1000);
searchbox = (WebElement) (((JavascriptExecutor) driver). executeScript("return tElementById('lst-ib');", searchbox));
ndKeys("hello");}}
Make sure you are using the right locator for it.
answered Feb 24 '17 at 6:17
1
**Different way to Find Element:**
ndElement(("id"));
ndElement(nkText("linkText"));
ndElement(("xpath"));
ndElement((". //*[@id='id']"));
ndElement(("//button[contains(., 'button name')]"));
ndElement(("//a[contains(., 'text name')]"));
ndElement(("//label[contains(., 'label name')]"));
ndElement(("//*[contains(text(), 'your text')]");
Check Case Sensitive:
ndElement(("//*[contains(lower-case(text()), 'your text')]");
For exact match:
ndElement(("//button[text()='your text']");
**Find NG-Element:**
Xpath == //td[contains(@ng-show, 'dLocation')]
CssSelector ==
answered Apr 12 '19 at 6:15
Although many browsers have $x(xPath) as a console built-in, here's an agggregation of the useful-but-hardcoded snippets from Introduction to using XPath in JavaScript ready for use in scripts:
Snapshot
This gives a one-off snapshot of the xpath result set. Data may be stale after DOM mutations.
const $x = xp => {
const snapshot = document. evaluate(
xp, document, null,
XPathResult. ORDERED_NODE_SNAPSHOT_TYPE, null);
return [.. (apshotLength)]
((_, i) => apshotItem(i));};
($x(‘//h2[contains(., “foo”)]’));
foo
foobar
bar
First ordered node
const $xOne = xp =>
document. evaluate(
RST_ORDERED_NODE_TYPE, null). singleNodeValue;
($xOne(‘//h2[contains(., “foo”)]’));
Iterator
Note however, that if the document is mutated (the document tree is modified) between iterations that will invalidate the iteration and the invalidIteratorState property of XPathResult is set to true, and a NS_ERROR_DOM_INVALID_STATE_ERR exception is thrown.
function *$xIter(xp) {
const iter = document. evaluate(
XPathResult. ORDERED_NODE_ITERATOR_TYPE, null);
for (;;) {
const node = erateNext();
if (! node) {
break;}
yield node;}}
// dump to array
([… $xIter(‘//h2[contains(., “foo”)]’)]);
// return next item from generator
const xpGen = $xIter(‘//h2[text()=”foo”]’);
(());
answered Jul 1 at 20:49
ggorlenggorlen29. 6k5 gold badges41 silver badges54 bronze badges
import;
tProperty(“”, “path of your chrome exe”);
WebDriver driver = new ChromeDriver();
()(). maximize();
ndElement((“. //*[@id=’UserName’]”))();
ndElement((“. //*[@id=’UserName’]”)). sendKeys(Email);
answered Sep 11 ’19 at 11:56
Not the answer you’re looking for? Browse other questions tagged javascript selenium selenium-webdriver xpath document. evaluate or ask your own question.
Introduction to using XPath in JavaScript – MDN Web Docs
This document describes the interface for using XPath in JavaScript internally, in extensions, and from websites. Mozilla implements a fair amount of the DOM 3 XPath, which means that XPath expressions can be run against both HTML and XML documents.
The main interface to using XPath is the evaluate function of the document cument. evaluateThis method evaluates XPath expressions against an XML based document (including HTML documents), and returns a XPathResult object, which can be a single node or a set of nodes. The existing documentation for this method is located at document. evaluate, but it is rather sparse for our needs at the moment; a more comprehensive examination will be given below.
var xpathResult = document. evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result);
ParametersThe evaluate function takes a total of five parameters:
xpathExpression: A string containing the XPath expression to be evaluated.
contextNode: A node in the document against which the xpathExpression should be evaluated, including any and all of its child nodes. The document node is the most commonly used.
namespaceResolver: A function that will be passed any namespace prefixes contained within xpathExpression which returns a string representing the namespace URI associated with that prefix. This enables conversion between the prefixes used in the XPath expressions and the possibly different prefixes used in the document. The function can be either:
Created by using the createNSResolver method of a XPathEvaluator object. You should use this virtually all of the time.
null, which can be used for HTML documents or when no namespace prefixes are used. Note that, if the xpathExpression contains a namespace prefix, this will result in a DOMException being thrown with the code NAMESPACE_ERR.
A custom user-defined function. See the Using a User Defined Namespace Resolver section in the appendix for details.
resultType: A constant that specifies the desired result type to be returned as a result of the evaluation. The most commonly passed constant is XPathResult. ANY_TYPE which will return the results of the XPath expression as the most natural type. There is a section in the appendix which contains a full list of the available constants. They are explained below in the section “Specifying the Return Type. ”
result: If an existing XPathResult object is specified, it will be reused to return the results. Specifying null will create a new XPathResult object.
Return ValueReturns xpathResult, which is an XPathResult object of the type specified in the resultType parameter. The XPathResult Interface is defined plementing a Default Namespace ResolverWe create a namespace resolver using the createNSResolver method of the document object.
var nsResolver = eateNSResolver( contextNode. ownerDocument == null? cumentElement: cumentElement);
Or alternatively by using the createNSResolver method of a XPathEvaluator object.
var xpEvaluator = new XPathEvaluator();
And then pass document. evaluate, the nsResolver variable as the namespaceResolver parameter.
Note: XPath defines QNames without a prefix to match only elements in the null namespace. There is no way in XPath to pick up the default namespace as applied to a regular element reference (e. g., p[@id=’_myid’] for ). To match default elements in a non-null namespace, you either have to refer to a particular element using a form such as [‘namespace-uri()=” and name()=’p’ and @id=’_myid’] (this approach works well for dynamic XPath’s where the namespaces might not be known) or use prefixed name tests, and create a namespace resolver mapping the prefix to the namespace. Read more on how to create a user-defined namespace resolver, if you wish to take the latter tesAdapts any DOM node to resolve namespaces so that an XPath expression can be easily evaluated relative to the context of the node where it appeared within the document. This adapter works like the DOM Level 3 method lookupNamespaceURI on nodes in resolving the namespaceURI from a given prefix using the current information available in the node’s hierarchy at the time lookupNamespaceURI is called. Also correctly resolves the implicit xml prefix. Specifying the Return TypeThe returned variable xpathResult from document. evaluate can either be composed of individual nodes (simple types), or a collection of nodes (node-set types).
Simple Types
When the desired result type in resultType is specified as either:
NUMBER_TYPE – a double
STRING_TYPE – a string
BOOLEAN_TYPE – a boolean
We obtain the returned value of the expression by accessing the following properties respectively of the XPathResult object.
numberValue
stringValue
booleanValue
Example
The following uses the XPath expression count(//p) to obtain the number of
elements in an HTML document:
var paragraphCount = document. evaluate( ‘count(//p)’, document, null, XPathResult. ANY_TYPE, null);
alert( ‘This document contains ‘ + mberValue + ‘ paragraph elements’);
Although JavaScript allows us to convert the number to a string for display, the XPath interface will not automatically convert the numerical result if the stringValue property is requested, so the following code will not work:
var paragraphCount = document. evaluate(‘count(//p)’, document, null, XPathResult. ANY_TYPE, null);
alert( ‘This document contains ‘ + ringValue + ‘ paragraph elements’);
Instead, it will return an exception with the code NS_DOM_TYPE_ERROR.
Node-Set Types
The XPathResult object allows node-sets to be returned in 3 principal different types:
Iterators
Snapshots
First Nodes
When the specified result type in the resultType parameter is either:
UNORDERED_NODE_ITERATOR_TYPE
ORDERED_NODE_ITERATOR_TYPE
The XPathResult object returned is a node-set of matched nodes which will behave as an iterator, allowing us to access the individual nodes contained by using the iterateNext() method of the XPathResult.
Once we have iterated over all of the individual matched nodes, iterateNext() will return null.
Note however, that if the document is mutated (the document tree is modified) between iterations that will invalidate the iteration and the invalidIteratorState property of XPathResult is set to true, and a NS_ERROR_DOM_INVALID_STATE_ERR exception is thrown.
var iterator = document. evaluate(‘//phoneNumber’, documentNode, null, RDERED_NODE_ITERATOR_TYPE, null);
try {
var thisNode = erateNext();
while (thisNode) {
alert( thisNode. textContent);
thisNode = erateNext();}}
catch (e) {
alert( ‘Error: Document tree modified during iteration ‘ + e);}
UNORDERED_NODE_SNAPSHOT_TYPE
ORDERED_NODE_SNAPSHOT_TYPE
The XPathResult object returned is a static node-set of matched nodes, which allows us to access each node through the snapshotItem(itemNumber) method of the XPathResult object, where itemNumber is the index of the node to be retrieved. The total number of nodes contained can be accessed through the snapshotLength property.
Snapshots do not change with document mutations, so unlike the iterators, the snapshot does not become invalid, but it may not correspond to the current document, for example, the nodes may have been moved, it might contain nodes that no longer exist, or new nodes could have been added.
var nodesSnapshot = document. evaluate(‘//phoneNumber’, documentNode, null, XPathResult. ORDERED_NODE_SNAPSHOT_TYPE, null);
for ( var i=0; i < apshotLength; i++)
{
alert( apshotItem(i). textContent);}
First Node
ANY_UNORDERED_NODE_TYPE
FIRST_ORDERED_NODE_TYPE
The XPathResult object returned is only the first found node that matched the XPath expression. This can be accessed through the singleNodeValue property of the XPathResult object. This will be null if the node set is empty.
Note that, for the unordered subtype the single node returned might not be the first in document order, but for the ordered subtype you are guaranteed to get the first matched node in the document order.
var firstPhoneNumber = document. evaluate('//phoneNumber', documentNode, null, RST_ORDERED_NODE_TYPE, null);
alert( 'The first phone number found is ' + ngleNodeValue. textContent);
The ANY_TYPE Constant
When the result type in the resultType parameter is specified as ANY_TYPE, the XPathResult object returned, will be whatever type that naturally results from the evaluation of the expression.
It could be any of the simple types (NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE), but, if the returned result type is a node-set then it will only be an UNORDERED_NODE_ITERATOR_TYPE.
To determine that type after evaluation, we use the resultType property of the XPathResult object. The constant values of this property are defined in the appendix. None Yet =====Any_Type Example=====
ExamplesWithin an HTML DocumentThe following code is intended to be placed in any JavaScript fragment within or linked to the HTML document against which the XPath expression is to be evaluated.
To extract all the
heading elements in an HTML document using XPath, the xpathExpression is ‘//h2’. Where, // is the Recursive Descent Operator that matches elements with the nodeName h2 anywhere in the document tree. The full code for this is: link to introductory xpath doc
var headings = document. evaluate(‘//h2’, document, null, XPathResult. ANY_TYPE, null);
Notice that, since HTML does not have namespaces, we have passed null for the namespaceResolver parameter.
Since we wish to search over the entire document for the headings, we have used the document object itself as the contextNode.
The result of this expression is an XPathResult object. If we wish to know the type of result returned, we may evaluate the resultType property of the returned object. In this case, that will evaluate to 4, an UNORDERED_NODE_ITERATOR_TYPE. This is the default return type when the result of the XPath expression is a node set. It provides access to a single node at a time and may not return nodes in a particular order. To access the returned nodes, we use the iterateNext() method of the returned object:
var thisHeading = erateNext();
var alertText = ‘Level 2 headings in this document are:n’
while (thisHeading) {
alertText += thisHeading. textContent + ‘n’;
thisHeading = erateNext();}
Once we iterate to a node, we have access to all the standard DOM interfaces on that node. After iterating through all the h2 elements returned from our expression, any further calls to iterateNext() will return null. Evaluating against an XML document within an ExtensionThe following uses an XML document located at chromeyourextension/content/ as an example.
xml version="1. 0"? >
202-456-1111
020 7925 0918
To make the contents of the XML document available within the extension, we create an XMLHttpRequest object to load the document synchronously, the variable xmlDoc will contain the document as an XMLDocument object against which we can use the evaluate method
JavaScript used in the extensions xul/js documents.
var req = new XMLHttpRequest();
(“GET”, “chromeyourextension/content/”, false);
(null);
var xmlDoc = sponseXML;
var nsResolver = eateNSResolver( xmlDoc. ownerDocument == null? cumentElement: cumentElement);
var personIterator = xmlDoc. evaluate(‘//person’, xmlDoc, nsResolver, XPathResult. ANY_TYPE, null);
NoteWhen the XPathResult object is not defined, the constants can be retrieved in privileged code using terfaces. nsIDOMXPathResult. ANY_TYPE (CI. nsIDOMXPathResult). Similarly, an XPathEvaluator can be created using:
asses[“;1″]. createInstance(terfaces. nsIDOMXPathEvaluator)
AppendixImplementing a User Defined Namespace Resolver
This is an example for illustration only. This function will need to take namespace prefixes from the xpathExpression and return the URI that corresponds to that prefix. For example, the expression:
‘//xhtml:td/mathml:math’
will select all MathML expressions that are the children of (X)HTML table data cell elements.
In order to associate the ‘mathml:’ prefix with the namespace URI ” and ‘xhtml:’ with the URI ” we provide a function:
function nsResolver(prefix) {
var ns = {
‘xhtml’: ”,
‘mathml’: ”};
return ns[prefix] || null;}
Our call to document. evaluate would then looks like:
document. evaluate( ‘//xhtml:td/mathml:math’, document, nsResolver, XPathResult. ANY_TYPE, null);
Implementing a default namespace for XML documents
As noted in the Implementing a Default Namespace Resolver previously, the default resolver does not handle the default namespace for XML documents. For example with this document:
xml version="1. 0" encoding="UTF-8"? >
Introduction to using XPath in JavaScript – MDN Web Docs
This document describes the interface for using XPath in JavaScript internally, in extensions, and from websites. Mozilla implements a fair amount of the DOM 3 XPath, which means that XPath expressions can be run against both HTML and XML documents.
The main interface to using XPath is the evaluate function of the document cument. evaluateThis method evaluates XPath expressions against an XML based document (including HTML documents), and returns a XPathResult object, which can be a single node or a set of nodes. The existing documentation for this method is located at document. evaluate, but it is rather sparse for our needs at the moment; a more comprehensive examination will be given below.
var xpathResult = document. evaluate( xpathExpression, contextNode, namespaceResolver, resultType, result);
ParametersThe evaluate function takes a total of five parameters:
xpathExpression: A string containing the XPath expression to be evaluated.
contextNode: A node in the document against which the xpathExpression should be evaluated, including any and all of its child nodes. The document node is the most commonly used.
namespaceResolver: A function that will be passed any namespace prefixes contained within xpathExpression which returns a string representing the namespace URI associated with that prefix. This enables conversion between the prefixes used in the XPath expressions and the possibly different prefixes used in the document. The function can be either:
Created by using the createNSResolver method of a XPathEvaluator object. You should use this virtually all of the time.
null, which can be used for HTML documents or when no namespace prefixes are used. Note that, if the xpathExpression contains a namespace prefix, this will result in a DOMException being thrown with the code NAMESPACE_ERR.
A custom user-defined function. See the Using a User Defined Namespace Resolver section in the appendix for details.
resultType: A constant that specifies the desired result type to be returned as a result of the evaluation. The most commonly passed constant is XPathResult. ANY_TYPE which will return the results of the XPath expression as the most natural type. There is a section in the appendix which contains a full list of the available constants. They are explained below in the section “Specifying the Return Type. ”
result: If an existing XPathResult object is specified, it will be reused to return the results. Specifying null will create a new XPathResult object.
Return ValueReturns xpathResult, which is an XPathResult object of the type specified in the resultType parameter. The XPathResult Interface is defined plementing a Default Namespace ResolverWe create a namespace resolver using the createNSResolver method of the document object.
var nsResolver = eateNSResolver( contextNode. ownerDocument == null? cumentElement: cumentElement);
Or alternatively by using the createNSResolver method of a XPathEvaluator object.
var xpEvaluator = new XPathEvaluator();
And then pass document. evaluate, the nsResolver variable as the namespaceResolver parameter.
Note: XPath defines QNames without a prefix to match only elements in the null namespace. There is no way in XPath to pick up the default namespace as applied to a regular element reference (e. g., p[@id=’_myid’] for ). To match default elements in a non-null namespace, you either have to refer to a particular element using a form such as [‘namespace-uri()=” and name()=’p’ and @id=’_myid’] (this approach works well for dynamic XPath’s where the namespaces might not be known) or use prefixed name tests, and create a namespace resolver mapping the prefix to the namespace. Read more on how to create a user-defined namespace resolver, if you wish to take the latter tesAdapts any DOM node to resolve namespaces so that an XPath expression can be easily evaluated relative to the context of the node where it appeared within the document. This adapter works like the DOM Level 3 method lookupNamespaceURI on nodes in resolving the namespaceURI from a given prefix using the current information available in the node’s hierarchy at the time lookupNamespaceURI is called. Also correctly resolves the implicit xml prefix. Specifying the Return TypeThe returned variable xpathResult from document. evaluate can either be composed of individual nodes (simple types), or a collection of nodes (node-set types).
Simple Types
When the desired result type in resultType is specified as either:
NUMBER_TYPE – a double
STRING_TYPE – a string
BOOLEAN_TYPE – a boolean
We obtain the returned value of the expression by accessing the following properties respectively of the XPathResult object.
numberValue
stringValue
booleanValue
Example
The following uses the XPath expression count(//p) to obtain the number of
elements in an HTML document:
var paragraphCount = document. evaluate( ‘count(//p)’, document, null, XPathResult. ANY_TYPE, null);
alert( ‘This document contains ‘ + mberValue + ‘ paragraph elements’);
Although JavaScript allows us to convert the number to a string for display, the XPath interface will not automatically convert the numerical result if the stringValue property is requested, so the following code will not work:
var paragraphCount = document. evaluate(‘count(//p)’, document, null, XPathResult. ANY_TYPE, null);
alert( ‘This document contains ‘ + ringValue + ‘ paragraph elements’);
Instead, it will return an exception with the code NS_DOM_TYPE_ERROR.
Node-Set Types
The XPathResult object allows node-sets to be returned in 3 principal different types:
Iterators
Snapshots
First Nodes
When the specified result type in the resultType parameter is either:
UNORDERED_NODE_ITERATOR_TYPE
ORDERED_NODE_ITERATOR_TYPE
The XPathResult object returned is a node-set of matched nodes which will behave as an iterator, allowing us to access the individual nodes contained by using the iterateNext() method of the XPathResult.
Once we have iterated over all of the individual matched nodes, iterateNext() will return null.
Note however, that if the document is mutated (the document tree is modified) between iterations that will invalidate the iteration and the invalidIteratorState property of XPathResult is set to true, and a NS_ERROR_DOM_INVALID_STATE_ERR exception is thrown.
var iterator = document. evaluate(‘//phoneNumber’, documentNode, null, RDERED_NODE_ITERATOR_TYPE, null);
try {
var thisNode = erateNext();
while (thisNode) {
alert( thisNode. textContent);
thisNode = erateNext();}}
catch (e) {
alert( ‘Error: Document tree modified during iteration ‘ + e);}
UNORDERED_NODE_SNAPSHOT_TYPE
ORDERED_NODE_SNAPSHOT_TYPE
The XPathResult object returned is a static node-set of matched nodes, which allows us to access each node through the snapshotItem(itemNumber) method of the XPathResult object, where itemNumber is the index of the node to be retrieved. The total number of nodes contained can be accessed through the snapshotLength property.
Snapshots do not change with document mutations, so unlike the iterators, the snapshot does not become invalid, but it may not correspond to the current document, for example, the nodes may have been moved, it might contain nodes that no longer exist, or new nodes could have been added.
var nodesSnapshot = document. evaluate(‘//phoneNumber’, documentNode, null, XPathResult. ORDERED_NODE_SNAPSHOT_TYPE, null);
for ( var i=0; i < apshotLength; i++)
{
alert( apshotItem(i). textContent);}
First Node
ANY_UNORDERED_NODE_TYPE
FIRST_ORDERED_NODE_TYPE
The XPathResult object returned is only the first found node that matched the XPath expression. This can be accessed through the singleNodeValue property of the XPathResult object. This will be null if the node set is empty.
Note that, for the unordered subtype the single node returned might not be the first in document order, but for the ordered subtype you are guaranteed to get the first matched node in the document order.
var firstPhoneNumber = document. evaluate('//phoneNumber', documentNode, null, RST_ORDERED_NODE_TYPE, null);
alert( 'The first phone number found is ' + ngleNodeValue. textContent);
The ANY_TYPE Constant
When the result type in the resultType parameter is specified as ANY_TYPE, the XPathResult object returned, will be whatever type that naturally results from the evaluation of the expression.
It could be any of the simple types (NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE), but, if the returned result type is a node-set then it will only be an UNORDERED_NODE_ITERATOR_TYPE.
To determine that type after evaluation, we use the resultType property of the XPathResult object. The constant values of this property are defined in the appendix. None Yet =====Any_Type Example=====
ExamplesWithin an HTML DocumentThe following code is intended to be placed in any JavaScript fragment within or linked to the HTML document against which the XPath expression is to be evaluated.
To extract all the
heading elements in an HTML document using XPath, the xpathExpression is ‘//h2’. Where, // is the Recursive Descent Operator that matches elements with the nodeName h2 anywhere in the document tree. The full code for this is: link to introductory xpath doc
var headings = document. evaluate(‘//h2’, document, null, XPathResult. ANY_TYPE, null);
Notice that, since HTML does not have namespaces, we have passed null for the namespaceResolver parameter.
Since we wish to search over the entire document for the headings, we have used the document object itself as the contextNode.
The result of this expression is an XPathResult object. If we wish to know the type of result returned, we may evaluate the resultType property of the returned object. In this case, that will evaluate to 4, an UNORDERED_NODE_ITERATOR_TYPE. This is the default return type when the result of the XPath expression is a node set. It provides access to a single node at a time and may not return nodes in a particular order. To access the returned nodes, we use the iterateNext() method of the returned object:
var thisHeading = erateNext();
var alertText = ‘Level 2 headings in this document are:n’
while (thisHeading) {
alertText += thisHeading. textContent + ‘n’;
thisHeading = erateNext();}
Once we iterate to a node, we have access to all the standard DOM interfaces on that node. After iterating through all the h2 elements returned from our expression, any further calls to iterateNext() will return null. Evaluating against an XML document within an ExtensionThe following uses an XML document located at chromeyourextension/content/ as an example.
xml version="1. 0"? >
202-456-1111
020 7925 0918
To make the contents of the XML document available within the extension, we create an XMLHttpRequest object to load the document synchronously, the variable xmlDoc will contain the document as an XMLDocument object against which we can use the evaluate method
JavaScript used in the extensions xul/js documents.
var req = new XMLHttpRequest();
(“GET”, “chromeyourextension/content/”, false);
(null);
var xmlDoc = sponseXML;
var nsResolver = eateNSResolver( xmlDoc. ownerDocument == null? cumentElement: cumentElement);
var personIterator = xmlDoc. evaluate(‘//person’, xmlDoc, nsResolver, XPathResult. ANY_TYPE, null);
NoteWhen the XPathResult object is not defined, the constants can be retrieved in privileged code using terfaces. nsIDOMXPathResult. ANY_TYPE (CI. nsIDOMXPathResult). Similarly, an XPathEvaluator can be created using:
asses[“;1″]. createInstance(terfaces. nsIDOMXPathEvaluator)
AppendixImplementing a User Defined Namespace Resolver
This is an example for illustration only. This function will need to take namespace prefixes from the xpathExpression and return the URI that corresponds to that prefix. For example, the expression:
‘//xhtml:td/mathml:math’
will select all MathML expressions that are the children of (X)HTML table data cell elements.
In order to associate the ‘mathml:’ prefix with the namespace URI ” and ‘xhtml:’ with the URI ” we provide a function:
function nsResolver(prefix) {
var ns = {
‘xhtml’: ”,
‘mathml’: ”};
return ns[prefix] || null;}
Our call to document. evaluate would then looks like:
document. evaluate( ‘//xhtml:td/mathml:math’, document, nsResolver, XPathResult. ANY_TYPE, null);
Implementing a default namespace for XML documents
As noted in the Implementing a Default Namespace Resolver previously, the default resolver does not handle the default namespace for XML documents. For example with this document:
xml version="1. 0" encoding="UTF-8"? >
Frequently Asked Questions about find element by xpath javascript
Can I use XPath with Javascript?
Mozilla implements a fair amount of the DOM 3 XPath, which means that XPath expressions can be run against both HTML and XML documents. …Jul 26, 2021
How do I get XPath elements?
Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.Mar 8, 2021
Is there a way to get element by XPath using Javascript in selenium Webdriver?
To identify a WebElement using xpath and javascript you have to use the evaluate() method which evaluates an xpath expression and returns a result.Dec 12, 2013