One of the interview questions asked is how to highlight the web elements in the page
Below is the answer
In Selenium we can use JavascriptExecutor (interface) to execute Javascript code into webdriver
In this post we will execute Javascript which will highlight the element.
Lets 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;
WebElement username= driver.findElement(By.id("email"));
// call the executeScript method
js.executeScript("arguments[0].setAttribute('style,'border: solid 2px red'')", username); // this code creates a block of solid red color around the email id text box
}
}
In this post we will execute Javascript which will highlight the element.
Lets 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;
WebElement username= driver.findElement(By.id("email"));
// call the executeScript method
js.executeScript("arguments[0].setAttribute('style,'border: solid 2px red'')", username); // this code creates a block of solid red color around the email id text box
}
}
if we want to just blink and go off as we have an option in QTP we can add one more line of code
js.executeScript("arguments[0].setAttribute('style,'border: solid 2px red'')", username); // this code creates a block of solid red color around the email id text box
js.executeScript("arguments[0].setAttribute("style,'border: "),username) // this code removes the block , so this above 2 lines of code will resemble the highlighting operation
Any comments please paste in Comment section
Its possible to take the screen shots while highlighting the element through selenium ???
ReplyDeletePlease reply me..
ReplyDelete