Test if an element is focused using Selenium Webdriver.

SeleniumAutomation TestingTesting Tools

We can test if an element is focused with Selenium webdriver. This is determined with the help of the activeElement() method. First of all we need to identify the element with help of any of the locators like id, class, name, xpath or css.

Syntax

driver.switchTo().activeElement();

Let us consider the below edit box and check if it is focused.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class ElementFocussed{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element
      WebElement l=driver.findElement(By.cssSelector(".gsc-input"));
      //activeElement() to verify element focused
      if(l.equals(driver.switchTo().activeElement()))
         System.out.println("Element is focused");
      else
         System.out.println("Element is not focused");
      driver.close();
   }
}

Output

raja
Published on 18-Sep-2020 17:10:50
Advertisements