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.
11 Answers
You can use document.evaluate:
Evaluates an XPath expression string and returns a result of the specified type if possible.
It is w3-standardized and whole documented:
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
console.log( getElementByXpath("//html[1]/body[1]/div[1]") );
<div>foo</div>
There's also a great introduction on mozilla developer network:
Alternative version, using XPathEvaluator:
function getElementByXPath(xpath) {
return new XPathEvaluator()
.createExpression(xpath)
.evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)
.singleNodeValue
}
console.log( getElementByXPath("//html[1]/body[1]/div[1]") );
<div>foo/bar</div>
In Chrome Dev Tools you can run the following:
$x("some xpath")
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 < nodesSnapshot.snapshotLength; i++ ){
result.push( nodesSnapshot.snapshotItem(i) );
}
return result;
}
This MDN overview helped:
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 passdocumentas 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.nullis 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 asXPathResult.ANY_TYPE, of the XPathResult constructor, which correspond to integers from 0 to 9.result: An existing XPathResult to use for the results.nullis the most common and will create a new XPathResult