Highlighting a Web Element on Webpage

If you’ve used UFT/QTP, then you must be familiar with this feature where it allows you to highlight the element selected or the element on focus. This is particularly useful since it allows the person performing test to know whether the code is able to recognize the element under test.

Many times while running Selenium tests, we want to know whether the element under test was successfully selected by the code. Also many times, we want to screenshot the element with a highlighted border so that we can verify that the element was actually worked or located by the code. A highlighted element is also helpful for debugging purposes, since it allows us to focus on the element , for which the code was actually intended.

However,Selenium, natively, doesn’t allows or gives any specific method to perform this highlighting. But this doesn’t mean we can’t achieve this. We can , certainly, with the power of code and with a little help from the JSExecutor that we have.


The crux of this code that we are going to use it that is uses the power of JS and JSExecutor to inject JavaScript , into the target application, or AUT. The code injects JS at run time so that the CSS properties of the element is changed. This change at run time, with the specified changed CSS allows us to highlight the element that we want to highlight.

To achieve this,we would create a new function, in a new file that would contain the code for highlighting. We will then simply call this in the program where we want.

import selenium
from selenium import webdriver
import time

def highlight(element):
    """Highlights a Selenium webdriver element"""
    driver = element._parent
    def apply_style(s):
        driver.execute_script("arguments[0].setAttribute('style', arguments[1])", element, s)
    orignal_style = element.get_attribute('style')
    apply_style("border: 4px solid red")
    if (element.get_attribute("style")!=None):



This is how it will work-

In the method apply_style(),

arguments[0].setAttribute('style',arguments[1]):– this line is injecting the CSS style tag into the element , and making its border settings with a 4px wide red line with solid look. We pass the style argument for this method, which contains the style information for this element. When the apply_style() method executes, it replaces, or injects, the custom JS code that we mentioned above.


Now, we simply call this method in our program , and pass the element that we need to be highlighted.

import unittest
from selenium import webdriver
from highlight_ele import highlight
from time import sleep

class JSExe(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome(chromepath)
    def test_JSExe(self):

        driver = self.driver
        ele = driver.find_element_by_xpath("//a[contains(text(),'Home')]")

    def tearDown(self):

if __name__ == '__main__':