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() 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 XPathResultAs 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, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
Snapshot: