Highlighting Elements in Selenium Java

HOME

package Web;

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;
import org.openqa.selenium.chrome.ChromeOptions;

import java.time.Duration;

public class HighlightText_Example {

    public static void main(String args[]) {

        ChromeOptions chromeOptions = new ChromeOptions();
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        driver.manage().window().maximize();

        try {
            driver.get("https://www.selenium.dev/");

            // identify the element
            WebElement element = driver.findElement(By.xpath("//*[@id='main_navbar']/ul/li[7]/div/a"));

            // Optionally, we wait to observe the element before changing the color
            Thread.sleep(1000);

            // Set the background color to yellow and the border to red
            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("arguments[0].style.backgroundColor = 'yellow'; arguments[0].style.border = '3px solid red';", element);

            // Optionally, we can wait to observe the highlight effect
            Thread.sleep(2000);
            System.out.println("Text is highlighted");

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally{
            // Closing browser
            driver.quit();
        }
    }
}

ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
driver.get("https://www.selenium.dev/");
WebElement element = driver.findElement(By.xpath("//*[@id='main_navbar']/ul/li[7]/div/a"));
  // Set the background color to yellow and the border to red
 JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.backgroundColor = 'yellow'; arguments[0].style.border = '3px solid red';", element);
 Thread.sleep(2000);
// Close the browser
driver.quit();