Pages

Saturday 21 February 2015

How to Highlight and Unhighlight an Element Using Selenium Web Driver?

Highlighting an element in the web page during execution may assists the tester to recognize the correct element execution in the project during automation process.

Here we will see how an element is highlighted before and after clicking on the particular element and taking the screenshots with the highlighted element. We will use the JavascriptExecutor interface to implement functionality in Selenium Web Driver.

Create a Class say element_Highlight as below:

package Your_Package_Name;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class element_Highlight {
 public void highlightElement(WebDriver driver,WebElement element) {  
  JavascriptExecutor js=(JavascriptExecutor) driver;
  js.executeScript("arguments[0].style.border='3px solid red'", element);
 }

 public void unhighlightLast(WebDriver driver,WebElement element) { 
  JavascriptExecutor js=(JavascriptExecutor) driver;
  js.executeScript("arguments[0].style.border='0px'", element);
 }
}

Now, call the highlightElement(Browser Object, element) method in your statement block of code as below:

public class Test2
{
final WebDriver driver;
element_Highlight eh= new element_Highlight();
public void EnterName(String username) { 
      rd.writereport(0, 1, username);
      WebElement e1=driver.findElement(By.xpath(c.getElementName("name")));
      eh.highlightElement(driver, e1);
      e1.sendKeys(username);
      eh.unhighlightLast(driver, e1); 
}



Many Thanks for your valuable comments and suggestions in advance.