πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 69 of 100
JavaScript Executor
Beginner

Highlighting Elements with JavaScript

πŸ’‘Scenario Overview

Highlighting Elements with JavaScript

Key Takeaways & Cheat Sheet

  • βœ“Execute JS script to alter element border CSS properties
  • βœ“Apply bright styles (e.g. solid 3px red) for high visibility
  • βœ“Revert styling changes after a brief timeout to restore original UI
  • βœ“Use as a debugging tool to capture highlighted failure screenshots

Short Direct Answer

Highlighting elements is a powerful technique for debugging and creating visual execution videos. Use `JavascriptExecutor` to change the border styling of your target element to a bright color (like solid red), capture a screenshot if needed, and restore the original styling afterwards.

⚠️ Senior Warning (Red Flag)

Do not leave highlight borders on elements permanently during test runs. It modifies the page layout and styling, which can interfere with subsequent tests.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Highlighting elements is especially useful in custom test listeners. If a test fails, you can highlight the failing element before capturing the failure screenshot.

SeleniumAutomation.java
Selenium 4 + Java
public static void highlightElement(WebDriver driver, WebElement element) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    // Store original element border style
    String originalStyle = element.getAttribute("style");
    
    // Set border to thick solid red
    js.executeScript("arguments[0].setAttribute('style', 'border: 3px solid red; background: yellow;');", element);
    
    // Pause briefly to show highlight (e.g. 500ms)
    try { Thread.sleep(500); } catch (InterruptedException e) {}
    
    // Restore original style
    js.executeScript("arguments[0].setAttribute('style', '" + originalStyle + "');", element);
}