Execute javaScript (locators) in selenium to identify HTML element

We have seen how to identify web elements using selenium locators...there are situations where selenium alone can't able to identify web elements, there we can execute javaScript commands in selenium...

JavaScript has it's own locators to identify web elements:

getElementById - Returns single element that matches the ID.


WebDriver driver;
driver = new FirefoxDriver();
driver.get("http://www.qavalidation.com/p/demo.html");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = null;
element = (WebElement) js.executeScript("return document.getElementById('username');");

getElementsByName - Returns list of web elements with name same as provided name.

getElementsByClassName - Returns list of elements with provided classname.

getElementsByTagName - Returns list of elements with provided tagname.
List labels = (List) js.executeScript("return document.getElementsByTagName('label');");
 for(WebElement label: labels)
 {
  //System.out.println(label.getAttribute("id"));
  System.out.println(label.getText());
 }

we can even use xpath and CSSSelector to identify HTML elements:
For CSSSelector, we use document.querySelector or document.querySelectorAll

document.querySelector returns 1st element in DOM that matches the CSSSelector provided.

Example:
public static void main(String[] args) {
 WebDriver driver;
 driver = new FirefoxDriver();
 driver.get("http://www.qavalidation.com/p/demo.html");
 JavascriptExecutor js = (JavascriptExecutor) driver;
 WebElement element = null;
 element = (WebElement) js.executeScript("return document.querySelector(\"input[name='uname']\");");
 element.sendKeys("MyName");
 }

Note: use escape double quotes (\" instead ") inside the querySelector argument to avoid error in execution.

document.querySelectorAll returns list of all html elements in DOM that matches the CSSSelector provided.
Note: Store the returned elements in a List and then do actions one by one either by for loop or iterator and perform actions on elements.

For more information on locating HTML elements, Refer:
http://www.w3schools.com/js/js_htmldom_elements.asp


No comments:

Post a Comment