Selenium does not provide the built-in methods to highlight WebElements on the web page. However, we can overcome and highlight any WebElement
using JavascriptExecutor
.
Code Snippet to highlight element with border:
We can set any color to highlight the element with border sizes like 2px, and 5px and pass the values in JavascriptExecutor parameters.
js.executeScript("arguments[0].style.border='2px solid black'", element);
js.executeScript("arguments[0].style.border='4px solid green'", element);
Code Snippet to highlight element with background:
We can set any color to highlight the element with a background color like red, blue, or yellow and pass the values in JavascriptExecutor parameters.
js.executeScript("arguments[0].style.background='LightGreen'", element);
js.executeScript("arguments[0].style.background='yellow'", element);
Java Example Code for Highlight WebElements using JavascriptExecutor
package TestAutomationCentral;
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 HighlightElement {
public static void main(String[] args) {
//TestAutomationCentral.com
System.setProperty("webdriver.chrome.driver", "C:\\temp\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
WebElement element = driver.findElement(By.name("q"));
JavascriptExecutor js = (JavascriptExecutor) driver;
//you can change the px and color accordingly for border
js.executeScript("arguments[0].style.border='2px solid black'", element);
//you can change color for background
js.executeScript("arguments[0].style.background='LightGreen'", element);
}
}