This post tells you, How to Scroll to the particular WebElement and Highlight it.In General we all wanted to know, on which element an action is going on.So, by scrolling to it and highlighting it solves the issue.
Just call the two methods ‘scrolltoElement’ & ‘highlightelement’ where ever you need.Keep all these methods in a Utils class and call whenever you need !!
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.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.Locatable;
import org.testng.annotations.Test;
public class Test123 {
WebDriver driver;
@Test
public void method46()
{
driver=new FirefoxDriver();
driver.get(“Your url”);
driver.manage().window().maximize();
WebElement element1= driver.findElement(By.xpath(“element xpath”));
//scolling to the webelement
scrolltoElement(element1);
//highlight that element
highlightelement(element1);
//performing clicking event
element1.click();
}
//method to scroll
public static void scrolltoElement(WebElement ScrolltoThisElement) {
Coordinates coordinate = ((Locatable) ScrolltoThisElement)
.getCoordinates();
coordinate.onPage();
coordinate.inViewPort();
}
//method to highlight
public static void highlightelement(WebElement element) {
for (int i = 0; i < 4; i++) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(
“arguments[0].setAttribute(‘style’, arguments[1]);”,
element, “color: yellow; border: 4px solid blue;”);
js.executeScript(
“arguments[0].setAttribute(‘style’, arguments[1]);”,
element, “”);
}
}
}