JavascriptExecutor can be used to highlight a web element in Selenium with Java.
A Selenium WebElement is passed to the executeScript() method of JavascriptExecutor, where JavaScript is executed to apply a CSS border style. This visual highlight helps testers identify elements during automation execution and debugging.
Below is an example automation script that demonstrates how to highlight a web element in Selenium using Java.
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 HighlightElement {
WebDriver driver = null;
@Test
public void highlight() {
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://google.com");
// Locate the web element
WebElement element = driver.findElement(By.Id("submit-btn"));
// Cast driver to JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
// Highlight the element with a red border
js.executeScript(
"arguments[0].style.border='1px solid red'", element
);
// Pause to see the highlighted element
Thread.sleep(3000);
driver.quit();
}
}