Test if an element is focused using Selenium Webdriver.
https://www.tutorialspoint.com/test-if-an-element-is-focused-using-selenium-webdriver
-
18-09-2020 - |
Question
Test if an element is focused using Selenium Webdriver.
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![](https://www.tutorialspoint.com/assets/questions/media/43295/activeelement.jpg)
Advertisements
Not affiliated with Tutorialspoint