Basic Selenium

How to highlight elements Selenium Webdriver using JavaScript

In Automation, testing sometimes element highlighter plays very important role. It helps us to track our execution flow which step is being processed. Some tools like QTP, Sahi etc. you will get this inbuilt feature. For Selenium, we have to write small code, which simply highlight element based on our parameter values. let’s get started and see Highlight element Selenium using CSS values.

 

Highlight element Selenium

 

In Selenium, we can use JavascriptExecutor (interface) to execute Javascript code into webdriver.

 

I have published video on the same which covers the same.

 

In this post we, will execute Javascript which will highlight the element

Let’s implement the same this will highlight the user name field.

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class Highlight {

 public static void main(String []args){
  
 WebDriver driver=new FirefoxDriver();
  
  driver.manage().window().maximize();
  
  driver.get("http://www.facebook.com");
  
 // Create the  JavascriptExecutor object
  JavascriptExecutor js=(JavascriptExecutor)driver; 
  
 // find element using id attribute
  WebElement username= driver.findElement(By.id("email"));  
  
 // call the executeScript method
  js.executeScript("arguments[0].setAttribute('style,'border: solid 2px red'');", username);
 }
  
}

In above program it, will highlight username field. Now we can not write every time the same code to highlight element so we will create reuse method and when we have to highlight element we will call the method.

 

Create highlight element method for reuse

public static void highLightElement(WebDriver driver, WebElement element)
{
JavascriptExecutor js=(JavascriptExecutor)driver; 

js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", element);

try 
{
Thread.sleep(500);
} 
catch (InterruptedException e) {

System.out.println(e.getMessage());
} 

js.executeScript("arguments[0].setAttribute('style','border: solid 2px white');", element); 

}

 

Complete program for Highlight element Selenium

package com.bog.htmldemo;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class aa {


public static void main(String []args){


WebDriver driver=new FirefoxDriver();

driver.manage().window().maximize();

driver.get("http://www.facebook.com");


// Inspect element
WebElement username= driver.findElement(By.id("email")); 

// Call reuse method
highLightElement(driver,username);

}

// Element highlighter code
public static void highLightElement(WebDriver driver, WebElement element)
{
JavascriptExecutor js=(JavascriptExecutor)driver; 

js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", element);

try 
{
Thread.sleep(1000);
} 
catch (InterruptedException e) {

System.out.println(e.getMessage());
} 

js.executeScript("arguments[0].setAttribute('style','border: solid 2px white');", element); 

}

}

You can also create a separate library for this and can you in other programs as well.

Try from your side and let me know if you finding some issue.

Please share with others as well. Keep visiting. Have a nice day 🙂

author-avatar

About Mukesh Otwani

I am Mukesh Otwani working professional in a beautiful city Bangalore India. I completed by BE from RGPV university Bhopal. I have passion towards automation testing since couple of years I started with Selenium then I got chance to work with other tools like Maven, Ant, Git, GitHub, Jenkins, Sikuli, Selenium Builder etc.

32 thoughts on “How to highlight elements Selenium Webdriver using JavaScript

  1. Ganesh says:

    I didn’t get u, can you make video on this. SO that we can use it in utilities

    1. Sure Ganesh will do that

  2. Trupti says:

    Hi in last few seconds of video you said customized method so we don’t have to call it again and again..So please can you share that?

    1. Hi Trupti,
      You can add it into the utility method while calling driver.findElement for the required locator. This has to integrate into frameowrk.

  3. Mouse says:

    The example you have above to highlight the username throws an exception when I tried it. I fixed the issue by changing it to:
    js.executeScript(“arguments[0].setAttribute(‘style’,’border: solid 2px red’)”, element)

    1. Hi Mouse,

      Thanks for bringing it up. I’ll make necessary changes into code fragment.

  4. Ajay says:

    Hi Mukesh,
    thanks.. its nice and quite handy!!
    in the top windows, i guess one of the single quotes has got misplaced in the below line of code. the closing quote for ‘style’ is missing, and after ‘red’ there is an extra one.
    js.executeScript(“arguments[0].setAttribute(‘style,’border: solid 2px red”);”, username);

    1. Hi Ajay,

      Thanks for pointing out this. This will others too.

  5. Sabbir says:

    Very handy code. Great work.

    1. Hi Sabbir,

      Thanks for your comments.

  6. Automation help says:

    In Highlight element Selenium video you mentioned about creating customize method for finding, highlighting Can you please ping me that code as in above case i have to call method for ever element in my frame work.

    1. Hi there,

      Create a method which accepts can accept id or xpath or etc as arguments and make its return type as WebElement for same method. Once you get WebElement as return type then execute driver operation inside your script.

      1. Automation Helper says:

        How to make this work for POM?

        1. Hi there,

          I didn’t get you. Please explain…

  7. Aravind says:

    Hi Mukesh
    In Highlight element Selenium video you mentioned about creating customize method for finding, highlighting and wait until element is found. Please ping me the video link.

  8. Liam says:

    Do i have to use Webelement in front of every driver.findElement to use this,
    do i have to keep repeating calling the function?

    1. Hi Liam,

      We use in the same way as I shown in video. We created a library and we are calling for every element.

      1. Azhar says:

        Hi Mukesh,
        How i can highlight partial text from link using this method, as this method will work for element?

        1. Hi Azhar,

          As per my knowledge, It is not possible to highlight partial text. Because WebElement will cover whole text.

  9. venkat says:

    Thanks mukesh ji.. with your blogs and videos i am also becoming very passionate about selenium automation. Thanks a ton for that.

    1. Hey Venkat,

      I am really glad to know that you got passion and interest. Keep learning and let me know if any help.

  10. sheshajee says:

    hi Mukesh,
    Can you reply the video link how can i write one time method which will highlight at every time of execution

    1. Hi Sheshajee,

      Yes you do that. Try to add highlighter code in below method as well.

  11. zeeshan says:

    Hi Mukesh,

    I am not able to understand the significance of below line of code used:

    js.executeScript(“arguments[0].setAttribute(‘style’, ‘background: yellow; border: 2px solid red;’);”, ele);

    Not sure where this “ele” is coming from as we have declared our webElement with the reference “element”

    1. Hi Zeeshan,

      Correct, You found the defect. It should be element.

      I have updated the document as well. Hope this highlighter worked for you.

  12. Nikhil says:

    Mukesh how do we understand Java Script, because unless we know syntax of it, its difficult to understand the above script.

    Post is really good

    1. Hi Nikhil,

      For Selenium you dont have to learn complete java script but still if you want to learn then w3school is best. http://www.w3schools.com/js/

  13. Gautham says:

    Hello Mukesh, Thanks for sharing this post. Its really helpful. I tried with IE 11 its not working any idea why?

    1. Yes Gautham it will work

  14. Nur Islam says:

    Excellent post.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.