How to highlight webelement in selenium and Java

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();
}

}

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x