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
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: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript
In Chrome Dev Tools you can run the following:
$x("some xpath")
Assuming your objective is to develop and test your xpath queries for screen maps. Then either use Chrome's developer tools. This allows you to run the xpath query to show the matches. Or in Firefox >9 you can do the same thing with the Web Developer Tools console. In earlier version use x-path-finder or Firebug.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
System.setProperty("webdriver.chrome.driver", "path of your chrome exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
driver.findElement(By.xpath(".//*[@id='UserName']")).clear();
driver.findElement(By.xpath(".//*[@id='UserName']")).sendKeys(Email);
You can use javascript's document.evaluate to run an XPath expression on the DOM. I think it's supported in one way or another in browsers back to IE 6.
MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate
IE supports selectNodes instead.
MSDN: https://msdn.microsoft.com/en-us/library/ms754523(v=vs.85).aspx
To direct to the point , you can easily use xapth .The exact and simple way to do this using the below code . Kindly try and provide feedback .Thank you .
JavascriptExecutor js = (JavascriptExecutor) driver;
//To click an element
WebElement element=driver.findElement(By.xpath(Xpath));
js.executeScript(("arguments[0].click();", element);
//To gettext
String theTextIWant = (String) js.executeScript("return arguments[0].value;",driver.findElement(By.xpath("//input[@id='display-name']")));
Further readings - https://medium.com/@smeesheady/webdriver-javascriptexecutor-interact-with-elements-and-open-and-handle-multiple-tabs-and-get-url-dcfda49bfa0f