Showing posts with label selenium.WebElement. Show all posts
Showing posts with label selenium.WebElement. Show all posts

Sunday, 29 December 2013

Selenium - How to highlight Element

It is always a good practice to highlight element before performing an operation. This helps us to know where the Selenium is currently focused or which element it is being executed.

There is no native way to do this, but because Selenium allows to execute JavaScript, it can be accomplished by  executing JavaScript method. Code is as follows -

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;
import org.testng.annotations.Test;

public class HighLightElement {

WebDriver driver = new FirefoxDriver(); //Launch firefox browser

@Test
   public void highlightTest() throws InterruptedException {
driver.get("https://www.facebook.com/"); // open facebook site
driver.manage().window().maximize(); // maximize browser
WebElement emailField = driver.findElement(By.xpath("//*[@id='email']")); //get
                reference to email text field
Thread.sleep(2000); //Stop program execution for 2 seconds
highlightElement(emailField); // call to highlight method


/** Method which executes Java Script code to highlight page object */
public void highlightElement(WebElement element) { 
   for (int i = 0; i < 2; i++) 
  { 
JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: red; border: 5px solid red;"); 
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, ""); 
     } 

}