Popular Searches
Popular Course Categories
Popular Courses

Highlight Elements

JavaScript with Selenium

<div class="selenium-notes">

<h1>Highlight Elements in Selenium WebDriver</h1>

<p><strong>Highlighting Elements</strong> in Selenium WebDriver is a useful technique for visually identifying a web element during automated test execution. Selenium does not provide a built-in <code>highlight()</code> method, so JavaScriptExecutor is commonly used to temporarily change the CSS properties of a WebElement, such as its border, outline, background color, or box shadow.</p>

<p>Highlighting is especially useful for debugging locators, understanding automation execution, demonstrating Selenium concepts, identifying the exact element being processed, and capturing screenshots during troubleshooting.</p>

<p>Selenium training commonly covers WebDriver, WebElements, locators, browser interactions, waits and synchronization, Actions, TestNG, Page Object Model, automation frameworks, reporting, debugging, and practical projects.</p>

<p><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

<hr>

<h2>1. What is Highlighting an Element?</h2>

<p>Highlighting an element means temporarily changing the visual appearance of a WebElement so that it can be easily identified on the webpage.</p>

<p>For example, a Selenium script can place a red border around a Login button before clicking it.</p>

<pre><code>WebElement loginButton =

    driver.findElement(By.id("login"));

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].style.border='3px solid red';",

    loginButton

);</code></pre>

<h2>2. Why Do We Highlight Elements?</h2>

<ul>

<li>To visually identify the element being automated.</li>

<li>To debug incorrect locators.</li>

<li>To demonstrate Selenium automation.</li>

<li>To understand the execution flow.</li>

<li>To troubleshoot failed test cases.</li>

<li>To create clearer debugging screenshots.</li>

<li>To help beginners understand WebDriver interactions.</li>

<li>To verify which element a locator has selected.</li>

</ul>

<h2>3. Is Highlighting Required for Selenium Automation?</h2>

<p>No. Highlighting is not required for normal Selenium automation. It is primarily a debugging, visualization, demonstration, and troubleshooting technique.</p>

<p>Selenium can locate and interact with an element without visually modifying it.</p>

<h2>4. Highlighting Element Flow</h2>

<pre><code>Launch Browser

      ↓

Open Web Application

      ↓

Locate WebElement

      ↓

Create JavascriptExecutor

      ↓

Modify Element CSS

      ↓

Element Becomes Highlighted

      ↓

Perform Selenium Action

      ↓

Validate Result

      ↓

Restore Style if Required</code></pre>

<h2>5. What is JavascriptExecutor?</h2>

<p><code>JavascriptExecutor</code> is a Selenium interface that allows Java code to execute JavaScript inside the browser.</p>

<pre><code>JavascriptExecutor js =

    (JavascriptExecutor) driver;</code></pre>

<h2>6. Basic Syntax for Highlighting</h2>

<pre><code>JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].style.border='3px solid red';",

    element

);</code></pre>

<h2>7. Understanding arguments[0]</h2>

<p>When a WebElement is passed to <code>executeScript()</code>, JavaScript receives it through the <code>arguments</code> object.</p>

<pre><code>js.executeScript(

    "arguments[0].style.border='3px solid red';",

    element

);</code></pre>

<ul>

<li><code>arguments[0]</code> represents the first argument.</li>

<li><code>element</code> is the WebElement passed from Java.</li>

<li><code>style.border</code> changes the element's border.</li>

</ul>

<h2>8. Highlight Using a Red Border</h2>

<pre><code>WebElement element =

    driver.findElement(By.id("username"));

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].style.border='3px solid red';",

    element

);</code></pre>

<h2>9. Highlight Using a Blue Border</h2>

<pre><code>js.executeScript(

    "arguments[0].style.border='3px solid blue';",

    element

);</code></pre>

<h2>10. Highlight Using a Green Border</h2>

<pre><code>js.executeScript(

    "arguments[0].style.border='3px solid green';",

    element

);</code></pre>

<h2>11. Highlight Using a Thick Border</h2>

<pre><code>js.executeScript(

    "arguments[0].style.border='5px solid red';",

    element

);</code></pre>

<h2>12. Highlight Using Outline</h2>

<p>An outline is another useful way to visually highlight an element.</p>

<pre><code>js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);</code></pre>

<p>An outline is often convenient for debugging because it generally does not change the element's layout dimensions like a border can.</p>

<h2>13. Highlight Using Background Color</h2>

<pre><code>js.executeScript(

    "arguments[0].style.backgroundColor='yellow';",

    element

);</code></pre>

<h2>14. Highlight Using Box Shadow</h2>

<pre><code>js.executeScript(

    "arguments[0].style.boxShadow='0 0 10px red';",

    element

);</code></pre>

<h2>15. Highlight Using Multiple CSS Properties</h2>

<pre><code>js.executeScript(

    "arguments[0].style.border='3px solid red';" +

    "arguments[0].style.backgroundColor='yellow';" +

    "arguments[0].style.boxShadow='0 0 10px red';",

    element

);</code></pre>

<h2>16. Highlight a Text Box</h2>

<pre><code>WebElement username =

    driver.findElement(By.id("username"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    username

);</code></pre>

<h2>17. Highlight a Password Field</h2>

<pre><code>WebElement password =

    driver.findElement(By.id("password"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    password

);</code></pre>

<h2>18. Highlight a Login Button</h2>

<pre><code>WebElement login =

    driver.findElement(By.id("login"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    login

);</code></pre>

<h2>19. Highlight a Submit Button</h2>

<pre><code>WebElement submit =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].style.border='4px solid green';",

    submit

);</code></pre>

<h2>20. Highlight a Checkbox</h2>

<pre><code>WebElement checkbox =

    driver.findElement(By.id("terms"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    checkbox

);</code></pre>

<h2>21. Highlight a Radio Button</h2>

<pre><code>WebElement radio =

    driver.findElement(By.id("male"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid blue';",

    radio

);</code></pre>

<h2>22. Highlight a Dropdown</h2>

<pre><code>WebElement dropdown =

    driver.findElement(By.id("country"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid green';",

    dropdown

);</code></pre>

<h2>23. Highlight a Link</h2>

<pre><code>WebElement link =

    driver.findElement(By.linkText("Contact Us"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    link

);</code></pre>

<h2>24. Highlight an Image</h2>

<pre><code>WebElement image =

    driver.findElement(By.cssSelector(".product-image"));

 

js.executeScript(

    "arguments[0].style.border='4px solid red';",

    image

);</code></pre>

<h2>25. Highlight a Table</h2>

<pre><code>WebElement table =

    driver.findElement(By.id("employeeTable"));

 

js.executeScript(

    "arguments[0].style.outline='4px solid blue';",

    table

);</code></pre>

<h2>26. Highlight a Table Row</h2>

<pre><code>WebElement row =

    driver.findElement(

        By.xpath("//table[@id='employees']//tr[5]")

    );

 

js.executeScript(

    "arguments[0].style.backgroundColor='yellow';" +

    "arguments[0].style.outline='3px solid red';",

    row

);</code></pre>

<h2>27. Highlight a Specific Table Cell</h2>

<pre><code>WebElement cell =

    driver.findElement(

        By.xpath("//table[@id='employees']//tr[5]/td[2]")

    );

 

js.executeScript(

    "arguments[0].style.backgroundColor='yellow';" +

    "arguments[0].style.border='3px solid red';",

    cell

);</code></pre>

<hr>

<h2>28. Highlight Multiple Elements</h2>

<p>Multiple elements can be highlighted by using <code>findElements()</code> and iterating through the returned list.</p>

<pre><code>List&lt;WebElement&gt; elements =

    driver.findElements(By.cssSelector(".product"));

 

for (WebElement element : elements) {

    js.executeScript(

        "arguments[0].style.outline='3px solid red';",

        element

    );

}</code></pre>

<h2>29. Highlight All Input Fields</h2>

<pre><code>List&lt;WebElement&gt; inputs =

    driver.findElements(By.tagName("input"));

 

for (WebElement input : inputs) {

    js.executeScript(

        "arguments[0].style.outline='2px solid blue';",

        input

    );

}</code></pre>

<h2>30. Highlight All Buttons</h2>

<pre><code>List&lt;WebElement&gt; buttons =

    driver.findElements(By.tagName("button"));

 

for (WebElement button : buttons) {

    js.executeScript(

        "arguments[0].style.outline='3px solid red';",

        button

    );

}</code></pre>

<h2>31. Highlight All Links</h2>

<pre><code>List&lt;WebElement&gt; links =

    driver.findElements(By.tagName("a"));

 

for (WebElement link : links) {

    js.executeScript(

        "arguments[0].style.outline='2px solid green';",

        link

    );

}</code></pre>

<h2>32. Highlight Element Before Clicking</h2>

<pre><code>WebElement button =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].style.outline='4px solid red';",

    button

);

 

button.click();</code></pre>

<h2>33. Highlight Element Before Typing</h2>

<pre><code>WebElement username =

    driver.findElement(By.id("username"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid blue';",

    username

);

 

username.sendKeys("admin");</code></pre>

<h2>34. Highlight Element Before Selecting</h2>

<pre><code>WebElement dropdown =

    driver.findElement(By.id("country"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid green';",

    dropdown

);

 

dropdown.click();</code></pre>

<h2>35. Highlight Element Before Mouse Hover</h2>

<pre><code>WebElement menu =

    driver.findElement(By.id("products"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    menu

);

 

new Actions(driver)

    .moveToElement(menu)

    .perform();</code></pre>

<h2>36. Highlight Before Double Click</h2>

<pre><code>WebElement item =

    driver.findElement(By.id("item"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid blue';",

    item

);

 

new Actions(driver)

    .doubleClick(item)

    .perform();</code></pre>

<h2>37. Highlight Before Right Click</h2>

<pre><code>WebElement item =

    driver.findElement(By.id("item"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid orange';",

    item

);

 

new Actions(driver)

    .contextClick(item)

    .perform();</code></pre>

<hr>

<h2>38. Create a Reusable Highlight Method</h2>

<p>In a real automation framework, repeated JavaScript code should be placed inside a reusable utility method.</p>

<pre><code>public void highlightElement(WebElement element) {

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].style.outline='3px solid red';",

        element

    );

}</code></pre>

<h2>39. Using the Reusable Method</h2>

<pre><code>WebElement login =

    driver.findElement(By.id("login"));

 

highlightElement(login);

 

login.click();</code></pre>

<h2>40. Reusable Method with Multiple Styles</h2>

<pre><code>public void highlightElement(WebElement element) {

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].style.border='3px solid red';" +

        "arguments[0].style.backgroundColor='yellow';" +

        "arguments[0].style.boxShadow='0 0 10px red';",

        element

    );

}</code></pre>

<h2>41. Highlight and Restore Original Style</h2>

<p>When highlighting is temporary, the original inline style can be stored and restored later.</p>

<pre><code>String originalStyle =

    element.getAttribute("style");

 

js.executeScript(

    "arguments[0].style.outline='4px solid red';",

    element

);

 

// Perform required operation

 

js.executeScript(

    "arguments[0].setAttribute('style', arguments[1]);",

    element,

    originalStyle

);</code></pre>

<h2>42. Why Restore the Original Style?</h2>

<ul>

<li>To prevent unnecessary modification of the webpage.</li>

<li>To keep screenshots closer to the original application.</li>

<li>To prevent debugging styles from affecting later checks.</li>

<li>To make the framework cleaner.</li>

<li>To avoid visual side effects in subsequent test steps.</li>

</ul>

<h2>43. Remove Border Highlight</h2>

<pre><code>js.executeScript(

    "arguments[0].style.border='';",

    element

);</code></pre>

<h2>44. Remove Outline Highlight</h2>

<pre><code>js.executeScript(

    "arguments[0].style.outline='';",

    element

);</code></pre>

<h2>45. Remove Background Highlight</h2>

<pre><code>js.executeScript(

    "arguments[0].style.backgroundColor='';",

    element

);</code></pre>

<h2>46. Highlight Using CSS Class</h2>

<p>Another approach is to define a CSS class for highlighting and add it dynamically.</p>

<pre><code>js.executeScript(

    "arguments[0].classList.add('selenium-highlight');",

    element

);</code></pre>

<h2>47. Example Highlight CSS Class</h2>

<pre><code>.selenium-highlight {

    outline: 3px solid red;

    box-shadow: 0 0 10px red;

}</code></pre>

<h2>48. Remove Highlight CSS Class</h2>

<pre><code>js.executeScript(

    "arguments[0].classList.remove('selenium-highlight');",

    element

);</code></pre>

<h2>49. Highlight and Scroll to Element</h2>

<p>If the element is outside the current viewport, it can first be brought into view and then highlighted.</p>

<pre><code>WebElement element =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].scrollIntoView({block:'center'});" +

    "arguments[0].style.outline='4px solid red';",

    element

);</code></pre>

<h2>50. Highlight Before Taking Screenshot</h2>

<pre><code>WebElement errorMessage =

    driver.findElement(By.id("error"));

 

js.executeScript(

    "arguments[0].style.outline='4px solid red';",

    errorMessage

);

 

// Capture screenshot here</code></pre>

<hr>

<h2>51. Highlight an Error Message</h2>

<pre><code>WebElement error =

    driver.findElement(

        By.cssSelector(".error")

    );

 

js.executeScript(

    "arguments[0].style.border='3px solid red';" +

    "arguments[0].style.backgroundColor='pink';",

    error

);</code></pre>

<h2>52. Highlight a Success Message</h2>

<pre><code>WebElement success =

    driver.findElement(

        By.cssSelector(".success")

    );

 

js.executeScript(

    "arguments[0].style.border='3px solid green';" +

    "arguments[0].style.backgroundColor='lightgreen';",

    success

);</code></pre>

<h2>53. Highlight a Warning Message</h2>

<pre><code>WebElement warning =

    driver.findElement(

        By.cssSelector(".warning")

    );

 

js.executeScript(

    "arguments[0].style.border='3px solid orange';" +

    "arguments[0].style.backgroundColor='yellow';",

    warning

);</code></pre>

<h2>54. Highlight a Product Card</h2>

<pre><code>WebElement product =

    driver.findElement(

        By.cssSelector(".product-card")

    );

 

js.executeScript(

    "arguments[0].style.outline='4px solid red';" +

    "arguments[0].style.boxShadow='0 0 15px red';",

    product

);</code></pre>

<h2>55. Highlight a Navigation Menu</h2>

<pre><code>WebElement menu =

    driver.findElement(

        By.cssSelector(".navigation")

    );

 

js.executeScript(

    "arguments[0].style.outline='3px solid blue';",

    menu

);</code></pre>

<h2>56. Highlight a Modal</h2>

<pre><code>WebElement modal =

    driver.findElement(

        By.cssSelector(".modal")

    );

 

js.executeScript(

    "arguments[0].style.outline='4px solid red';",

    modal

);</code></pre>

<h2>57. Highlight a Form Section</h2>

<pre><code>WebElement form =

    driver.findElement(

        By.id("registrationForm")

    );

 

js.executeScript(

    "arguments[0].style.outline='4px solid green';",

    form

);</code></pre>

<hr>

<h2>58. Highlighting with Page Object Model</h2>

<p>Highlighting can be included in a reusable BasePage or utility class in a Page Object Model framework.</p>

<pre><code>public class BasePage {

 

    protected WebDriver driver;

 

    public BasePage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void highlightElement(WebElement element) {

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style.outline='3px solid red';",

            element

        );

    }

}</code></pre>

<h2>59. Login Page Example</h2>

<pre><code>public class LoginPage extends BasePage {

 

    private By username =

        By.id("username");

 

    private By password =

        By.id("password");

 

    private By loginButton =

        By.id("login");

 

    public LoginPage(WebDriver driver) {

        super(driver);

    }

 

    public void highlightLoginFields() {

 

        highlightElement(

            driver.findElement(username)

        );

 

        highlightElement(

            driver.findElement(password)

        );

 

        highlightElement(

            driver.findElement(loginButton)

        );

    }

}</code></pre>

<h2>60. Highlight Utility Class</h2>

<pre><code>public class HighlightUtils {

 

    public static void highlight(

        WebDriver driver,

        WebElement element

    ) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style.outline='3px solid red';",

            element

        );

    }

 

    public static void removeHighlight(

        WebDriver driver,

        WebElement element

    ) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style.outline='';",

            element

        );

    }

}</code></pre>

<h2>61. Using HighlightUtils</h2>

<pre><code>WebElement button =

    driver.findElement(By.id("submit"));

 

HighlightUtils.highlight(

    driver,

    button

);

 

button.click();</code></pre>

<h2>62. Highlight with Explicit Wait</h2>

<p>Highlighting should not be used as a synchronization mechanism. If an element is dynamically loaded, wait for the required condition first.</p>

<pre><code>WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

    );

 

WebElement element = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("submit")

    )

);

 

HighlightUtils.highlight(

    driver,

    element

);</code></pre>

<h2>63. Highlight Before Click with Explicit Wait</h2>

<pre><code>WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

    );

 

WebElement button = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("submit")

    )

);

 

HighlightUtils.highlight(

    driver,

    button

);

 

button.click();</code></pre>

<h2>64. Highlight Dynamic Element</h2>

<pre><code>WebElement element = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("dynamicElement")

    )

);

 

HighlightUtils.highlight(

    driver,

    element

);</code></pre>

<hr>

<h2>65. Highlight Element Inside iframe</h2>

<p>When an element is inside an iframe, switch to the correct frame before locating and highlighting the element.</p>

<pre><code>WebElement frame =

    driver.findElement(By.id("paymentFrame"));

 

driver.switchTo().frame(frame);

 

WebElement paymentButton =

    driver.findElement(By.id("pay"));

 

HighlightUtils.highlight(

    driver,

    paymentButton

);

 

driver.switchTo().defaultContent();</code></pre>

<h2>66. Highlight Element Inside a Modal</h2>

<pre><code>WebElement modal =

    driver.findElement(

        By.cssSelector(".modal")

    );

 

WebElement target =

    modal.findElement(

        By.cssSelector(".target")

    );

 

HighlightUtils.highlight(

    driver,

    target

);</code></pre>

<h2>67. Highlight Element in a Table</h2>

<pre><code>WebElement employee =

    driver.findElement(

        By.xpath("//table//tr[5]")

    );

 

HighlightUtils.highlight(

    driver,

    employee

);</code></pre>

<h2>68. Highlight Element During Login Automation</h2>

<pre><code>WebElement username =

    driver.findElement(By.id("username"));

 

WebElement password =

    driver.findElement(By.id("password"));

 

WebElement login =

    driver.findElement(By.id("login"));

 

HighlightUtils.highlight(

    driver,

    username

);

 

username.sendKeys("admin");

 

HighlightUtils.highlight(

    driver,

    password

);

 

password.sendKeys("admin123");

 

HighlightUtils.highlight(

    driver,

    login

);

 

login.click();</code></pre>

<h2>69. Highlight Elements During Registration</h2>

<pre><code>WebElement firstName =

    driver.findElement(By.id("firstName"));

 

WebElement email =

    driver.findElement(By.id("email"));

 

WebElement register =

    driver.findElement(By.id("register"));

 

HighlightUtils.highlight(

    driver,

    firstName

);

 

firstName.sendKeys("John");

 

HighlightUtils.highlight(

    driver,

    email

);

 

email.sendKeys("[email protected]");

 

HighlightUtils.highlight(

    driver,

    register

);

 

register.click();</code></pre>

<h2>70. Highlight Elements During E-Commerce Testing</h2>

<pre><code>WebElement search =

    driver.findElement(By.id("search"));

 

WebElement product =

    driver.findElement(

        By.cssSelector(".product-card")

    );

 

WebElement cart =

    driver.findElement(By.id("cart"));

 

HighlightUtils.highlight(

    driver,

    search

);

 

search.sendKeys("Laptop");

 

HighlightUtils.highlight(

    driver,

    product

);

 

HighlightUtils.highlight(

    driver,

    cart

);</code></pre>

<h2>71. Highlight Elements During Checkout</h2>

<pre><code>WebElement address =

    driver.findElement(By.id("address"));

 

WebElement payment =

    driver.findElement(By.id("payment"));

 

WebElement order =

    driver.findElement(By.id("placeOrder"));

 

HighlightUtils.highlight(

    driver,

    address

);

 

HighlightUtils.highlight(

    driver,

    payment

);

 

HighlightUtils.highlight(

    driver,

    order

);</code></pre>

<hr>

<h2>72. Highlighting for Locator Debugging</h2>

<p>Highlighting is useful when a page contains multiple similar elements. It can help determine which element a locator actually selected.</p>

<pre><code>WebElement element =

    driver.findElement(

        By.xpath("//button[contains(text(),'Submit')]")

    );

 

HighlightUtils.highlight(

    driver,

    element

);</code></pre>

<h2>73. Highlighting Does Not Validate a Locator</h2>

<p>A locator can successfully return an element while still selecting the wrong element. Therefore, after locating an element, verify its text, attributes, position, or other relevant properties when necessary.</p>

<h2>74. Highlighting Does Not Make an Element Clickable</h2>

<p>Adding a border or outline does not make a hidden, disabled, covered, or otherwise non-interactable element clickable.</p>

<h2>75. Highlighting Does Not Replace Explicit Waits</h2>

<p>Highlighting only changes the appearance of an element. It does not wait for the element to become visible, enabled, clickable, or ready for interaction.</p>

<h2>76. Highlighting and Element State</h2>

<p>Before interacting with an element, the test may need to check:</p>

<ul>

<li>Whether the element is displayed.</li>

<li>Whether the element is enabled.</li>

<li>Whether the element is selected when applicable.</li>

<li>Whether the correct frame is selected.</li>

<li>Whether the correct browser window or tab is active.</li>

<li>Whether an overlay is blocking the element.</li>

</ul>

<h2>77. Highlight a Displayed Element</h2>

<pre><code>if (element.isDisplayed()) {

    HighlightUtils.highlight(

        driver,

        element

    );

}</code></pre>

<h2>78. Highlight an Enabled Element</h2>

<pre><code>if (element.isEnabled()) {

    HighlightUtils.highlight(

        driver,

        element

    );

}</code></pre>

<h2>79. Highlight a Selected Checkbox</h2>

<pre><code>if (checkbox.isSelected()) {

    HighlightUtils.highlight(

        driver,

        checkbox

    );

}</code></pre>

<hr>

<h2>80. Common Mistakes While Highlighting Elements</h2>

<ul>

<li>Using highlighting as a replacement for explicit waits.</li>

<li>Using highlighting as a solution for click failures.</li>

<li>Using an incorrect locator.</li>

<li>Ignoring iframe or window context.</li>

<li>Leaving debugging styles on the page unnecessarily.</li>

<li>Highlighting every element without a debugging purpose.</li>

<li>Changing CSS properties that affect page layout.</li>

<li>Assuming a highlighted element is automatically valid.</li>

</ul>

<h2>81. Common Mistake: Using Highlighting as a Click Fix</h2>

<p>If a click fails, highlighting does not solve the underlying problem. Investigate the locator, synchronization, overlays, visibility, enabled state, stale elements, frame context, and other interaction conditions.</p>

<h2>82. Common Mistake: Changing Layout with Border</h2>

<p>Depending on the element's CSS box model, adding a border can affect dimensions or layout. An outline is often a safer visual debugging option.</p>

<h2>83. Common Mistake: Not Restoring Styles</h2>

<p>If the test performs visual comparisons, screenshot validation, or CSS-related checks, temporary highlighting can interfere with those validations. Restore the original style when required.</p>

<h2>84. Best Practice: Use a Utility</h2>

<pre><code>public void highlightElement(WebElement element) {

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].style.outline='3px solid red';",

        element

    );

}</code></pre>

<h2>85. Best Practice: Use Highlighting Selectively</h2>

<p>Highlight only the elements that need to be investigated or demonstrated. This keeps the automation execution easier to understand and avoids unnecessary JavaScript operations.</p>

<h2>86. Best Practice: Combine Highlighting with Logging</h2>

<pre><code>System.out.println(

    "Highlighting Login button"

);

 

HighlightUtils.highlight(

    driver,

    loginButton

);</code></pre>

<h2>87. Best Practice: Highlight Before Important Actions</h2>

<pre><code>HighlightUtils.highlight(

    driver,

    submitButton

);

 

submitButton.click();</code></pre>

<h2>88. Best Practice: Validate After the Action</h2>

<pre><code>HighlightUtils.highlight(

    driver,

    submitButton

);

 

submitButton.click();

 

WebElement success =

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("success")

        )

    );</code></pre>

<hr>

<h2>89. Highlighting in Debug Mode</h2>

<p>A framework can enable highlighting only when debugging is required.</p>

<pre><code>boolean debugMode = true;

 

if (debugMode) {

    HighlightUtils.highlight(

        driver,

        element

    );

}

 

element.click();</code></pre>

<h2>90. Configuration-Based Highlighting</h2>

<pre><code>if (Config.isHighlightEnabled()) {

    HighlightUtils.highlight(

        driver,

        element

    );

}</code></pre>

<h2>91. Highlighting and Screenshots</h2>

<p>Highlighting can make screenshots easier to understand by showing the exact element involved in a test step.</p>

<pre><code>HighlightUtils.highlight(

    driver,

    targetElement

);

 

// Capture screenshot here</code></pre>

<h2>92. Highlighting Failed Elements</h2>

<pre><code>if (!actualText.equals(expectedText)) {

    HighlightUtils.highlight(

        driver,

        resultElement

    );

 

    System.out.println(

        "Validation failed"

    );

}</code></pre>

<h2>93. Highlighting Multiple Invalid Fields</h2>

<pre><code>List&lt;WebElement&gt; invalidFields =

    driver.findElements(

        By.cssSelector(".invalid")

    );

 

for (WebElement field : invalidFields) {

    HighlightUtils.highlight(

        driver,

        field

    );

}</code></pre>

<hr>

<h2>94. Complete Highlight Utility</h2>

<pre><code>public class HighlightUtils {

 

    public static void highlight(

        WebDriver driver,

        WebElement element

    ) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style.outline='3px solid red';" +

            "arguments[0].style.boxShadow='0 0 10px red';",

            element

        );

    }

 

    public static void removeHighlight(

        WebDriver driver,

        WebElement element

    ) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style.outline='';" +

            "arguments[0].style.boxShadow='';",

            element

        );

    }

}</code></pre>

<h2>95. Complete Login Example</h2>

<pre><code>import java.time.Duration;

 

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.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class HighlightExample {

 

    public static void main(String[] args) {

 

        WebDriver driver =

            new ChromeDriver();

 

        try {

 

            driver.manage()

                  .window()

                  .maximize();

 

            driver.get("https://example.com");

 

            WebDriverWait wait =

                new WebDriverWait(

                    driver,

                    Duration.ofSeconds(10)

                );

 

            WebElement username = wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.id("username")

                )

            );

 

            JavascriptExecutor js =

                (JavascriptExecutor) driver;

 

            js.executeScript(

                "arguments[0].style.outline='3px solid red';",

                username

            );

 

            username.sendKeys("admin");

 

            WebElement password =

                driver.findElement(

                    By.id("password")

                );

 

            js.executeScript(

                "arguments[0].style.outline='3px solid blue';",

                password

            );

 

            password.sendKeys("admin123");

 

            WebElement login =

                driver.findElement(

                    By.id("login")

                );

 

            js.executeScript(

                "arguments[0].style.outline='3px solid green';",

                login

            );

 

            login.click();

 

        } finally {

            driver.quit();

        }

    }

}</code></pre>

<h2>96. Highlighting with TestNG</h2>

<pre><code>import org.testng.annotations.Test;

 

public class HighlightTest {

 

    @Test

    public void highlightTest() {

 

        WebElement button =

            driver.findElement(By.id("submit"));

 

        HighlightUtils.highlight(

            driver,

            button

        );

 

        button.click();

    }

}</code></pre>

<h2>97. Highlighting in an Automation Framework</h2>

<pre><code>Test Case

   ↓

Page Object

   ↓

Locate Element

   ↓

Wait for Element

   ↓

Highlight Element

   ↓

Perform Action

   ↓

Validate Result

   ↓

Remove Highlight if Required

   ↓

Report Result</code></pre>

<hr>

<h2>98. Interview Question: What is Highlighting an Element?</h2>

<p>Highlighting an element means temporarily changing its CSS appearance through JavaScript so that it becomes visually noticeable during Selenium execution.</p>

<h2>99. Interview Question: How Do You Highlight an Element?</h2>

<pre><code>JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].style.border='3px solid red';",

    element

);</code></pre>

<h2>100. Interview Question: Why is JavascriptExecutor Used?</h2>

<p>JavaScript can directly modify DOM and CSS properties. Selenium does not provide a dedicated native <code>highlight()</code> method, so JavaScriptExecutor is commonly used for this purpose.</p>

<h2>101. Interview Question: What is arguments[0]?</h2>

<p><code>arguments[0]</code> represents the first parameter passed to the JavaScript executed by Selenium.</p>

<h2>102. Interview Question: Does Highlighting Make an Element Clickable?</h2>

<p>No. Highlighting changes the visual appearance only. It does not make a hidden, disabled, covered, or non-interactable element clickable.</p>

<h2>103. Interview Question: Does Highlighting Replace Explicit Wait?</h2>

<p>No. Explicit waits and highlighting serve different purposes. Explicit waits synchronize the test with application state, while highlighting provides visual feedback.</p>

<h2>104. Interview Question: Can Multiple Elements Be Highlighted?</h2>

<p>Yes. Use <code>findElements()</code> and iterate over the returned list.</p>

<h2>105. Interview Question: How Can You Remove Highlighting?</h2>

<pre><code>js.executeScript(

    "arguments[0].style.outline='';",

    element

);</code></pre>

<h2>106. Interview Question: Border vs Outline?</h2>

<p>Both can visually highlight an element. An outline is often convenient for debugging because it generally does not occupy layout space.</p>

<h2>107. Interview Question: Can Highlighting Affect a Test?</h2>

<p>Yes. Because highlighting modifies CSS or DOM state, it can affect the visual appearance and, depending on the property used, potentially affect layout. Therefore it should normally be treated as a debugging modification.</p>

<h2>108. Interview Question: Should Every Element Be Highlighted?</h2>

<p>No. Highlighting should generally be used selectively for debugging, demonstration, or troubleshooting.</p>

<hr>

<h2>109. Quick Revision Table</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Purpose</th><th>Code / Technique</th></tr>

<tr><td>Create JavaScript Executor</td><td><code>JavascriptExecutor js = (JavascriptExecutor) driver;</code></td></tr>

<tr><td>Red Border</td><td><code>style.border='3px solid red'</code></td></tr>

<tr><td>Red Outline</td><td><code>style.outline='3px solid red'</code></td></tr>

<tr><td>Background Highlight</td><td><code>style.backgroundColor='yellow'</code></td></tr>

<tr><td>Shadow Highlight</td><td><code>style.boxShadow='0 0 10px red'</code></td></tr>

<tr><td>JavaScript Element Reference</td><td><code>arguments[0]</code></td></tr>

<tr><td>Add CSS Class</td><td><code>classList.add()</code></td></tr>

<tr><td>Remove CSS Class</td><td><code>classList.remove()</code></td></tr>

<tr><td>Remove Outline</td><td><code>style.outline=''</code></td></tr>

</table>

<h2>110. Highlight Elements Checklist</h2>

<ul>

<li>Locate the correct WebElement.</li>

<li>Use a reliable locator.</li>

<li>Create JavascriptExecutor when required.</li>

<li>Apply a temporary visual style.</li>

<li>Prefer outline when layout modification should be avoided.</li>

<li>Use explicit waits separately for synchronization.</li>

<li>Use native Selenium interactions for normal user actions.</li>

<li>Restore the original style when required.</li>

<li>Use reusable utility methods.</li>

<li>Enable highlighting selectively in larger frameworks.</li>

<li>Validate actual application behavior after interaction.</li>

</ul>

<h2>111. Best Practice Summary</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Area</th><th>Recommended Practice</th></tr>

<tr><td>Purpose</td><td>Use highlighting mainly for debugging and visualization</td></tr>

<tr><td>JavaScript</td><td>Use JavascriptExecutor for temporary CSS/DOM changes</td></tr>

<tr><td>Visual Style</td><td>Use outline when appropriate</td></tr>

<tr><td>Synchronization</td><td>Use explicit waits independently</td></tr>

<tr><td>Interaction</td><td>Use Selenium APIs for normal interactions</td></tr>

<tr><td>Framework</td><td>Create reusable highlight utilities</td></tr>

<tr><td>Debugging</td><td>Highlight only the element being investigated</td></tr>

<tr><td>Cleanup</td><td>Restore styles when necessary</td></tr>

<tr><td>Validation</td><td>Verify the actual application result</td></tr>

</table>

<h2>112. Final Practical Workflow</h2>

<pre><code>Launch Browser

      ↓

Open Application

      ↓

Locate WebElement

      ↓

Wait for Required Condition

      ↓

Highlight Element

      ↓

Perform Selenium Action

      ↓

Validate Result

      ↓

Remove Highlight if Required

      ↓

Capture Screenshot/Report

      ↓

Continue Test</code></pre>

<h2>113. Conclusion</h2>

<p><strong>Highlight Elements</strong> is a useful Selenium WebDriver technique for visually identifying WebElements during automated test execution. It is commonly implemented with <code>JavascriptExecutor</code> by modifying CSS properties such as border, outline, background color, or box shadow.</p>

<p>The technique is useful for debugging locators, demonstrating automation workflows, troubleshooting failed interactions, identifying target elements, and creating clearer screenshots. However, highlighting does not replace explicit waits, element validation, reliable locators, or normal Selenium interactions.</p>

<p>For maintainable automation frameworks, highlighting can be implemented as a reusable utility and enabled only when debugging or visual demonstration is required.</p>

<p><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training Course</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

</div>

Previous Next
whatsapp