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 + Javapublic 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);
}