Problem:

We have a contact form with Name, Email and Comment fields, and if invalid data is entered to the fields, the validation system will highlight that field and it will be focused, so the user can change it quickly. In our tests we want to check if the proper field gets the focus.

<div class="contact-form">
    <label> Name </label>
    <input id="contact-name" type="text" />
    <label> Email </label>
    <input id="contact-email" type="text" />
    <label> Comment </label>
    <input id="contact-comment" type="text" />
</div>

(this is just an example code, and not a functional one)

Solution:

Selenium suggest to use css selectors, so we will start with that. To see if the element has the focus we will use css pseudo-class “:focus” and check if an element is present like this:

Assert.IsTrue(selenium.IsElementPresent("css=#contact-name:focus"));

This looks quite nice and easy, but you may encounter some problems with it. The element #contact-name can be found, but #contact-name:focus can not. In this case we have to think outside of the box, and come up with another solution. We can use the Javascript DOM locator to get the element that is selected (has focus), and compare it to the element we expect to have focus:

Assert.AreEqual(selenium.GetElementIndex("dom=document.activeElement"),
selenium.GetElementIndex("css=#contact-name"));

Similar Posts from the author:

2 thoughts to “Selenium – How to check if an element has focus

  • Vidur Puri

    What if we want to use WedDriver instead of Selenium.?

    • Szabolcs Varsandán

      Hi,

      WebElement in Webdriver has it’s own equals defined so we can just use equals to check focus:
      element.equals(driver.switchTo().activeElement())

Comments are closed.