How to highlight elements in WebDriver during runtime
In web automation-testing, element highlighter plays a very important role. It helps to track the exact step to be performed. UFT/QTP like testing tool is capable to highlight an element in run time because you will get this feature inbuilt with this tool. In Selenium there is no such feature available so we need to write our own code to highlight element.
Highlighting element is also useful for debugging the code.One way to know steps being performed in the browser is to highlight the web page elements.
The core to use "JavaScriptExecutor" to inject javascript in your application and change the CSS for the element, like create a border for the element.
Sample code
The core to use "JavaScriptExecutor" to inject javascript in your application and change the CSS for the element, like create a border for the element.
Sample code
JavascriptExecutor js=(JavascriptExecutor)driver;
js.executeScript("arguments[0].style.border='4px groove red'", Element);
Explanation
Arguments[0].style.border:- this script is injecting the CSS style tag into the element and making its border settings with a 4px wide red line with groove look.
Element: - This is the element around which border will be drawn.
I am creating a method which could be reusable for highlighting the test element.
Element Highlight method
public void HighlightElement(WebDriver driver, WebElement elm){
try{
JavascriptExecutor js=(JavascriptExecutor)driver;
js.executeScript("arguments[0].style.border='4px groove red'", elm);
Thread.sleep(1000);
js.executeScript("arguments[0].style.border=''", elm);
}catch(Exception e){
System.out.println(e);
}
}px groove red'", email);
Video
Complete code
package com.selenium.sampleseleniumproject;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class AppTest3 {
protected WebDriver driver;
@Test
public void Highlight() throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\anjan\\Desktop\\cucmber\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://www.faceboo.com");
driver.manage().window().maximize();
WebElement email = driver.findElement(By.xpath("//*[@id='email']"));
WebElement pass = driver.findElement(By.xpath("//*[@id='pass']"));
HighlightElement(driver, email);
email.sendKeys("[email protected]");
HighlightElement(driver, pass);
pass.sendKeys("password");
// close browser
driver.close();
}
public void HighlightElement(WebDriver driver, WebElement elm) {
try {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.border='4px groove red'", elm);
Thread.sleep(1000);
js.executeScript("arguments[0].style.border=''", elm);
} catch (Exception e) {
System.out.println(e);
}
}
}