Find “Cursor” position or currently focused element in a web page with Selenium

Problem Statement: On your registration page, you entered valid values in a few mandatory fields but submit the form with no values in a few of the mandatory fields. Now along with the error message(s), you want to verify that your cursor position is in the correct field (current focused element) like in the first blank mandatory field using Selenium.

Solution:

There are many ways to validate that but the simplest one would be to use:> driver.switchTo().activeElement()

Use:

Switches to the element that currently has focus within the document currently “switched to”, or the body element if this cannot be detected. This matches the semantics of calling “document.activeElement” in JavaScript.

Returns:

The Web Element with focus, or the body element if no element with the focus can be detected.

And then you can put assertion based on your expected focused element, something like:

Assert.assertTrue(driver.findElement(By.xpath(“//input[@type=’password’]”)).equals(driver.switchTo().activeElement()));

#testAutomation #seleniumJava #focusedElement #automationTest #anotherStory

I’m weird. I’m a weirdo.