Correct way to focus an element in Selenium WebDriver using Java

The following code –


tries to find an input tag box to enter some information, while

new Actions(driver).moveToElement(element).perform();

is more appropriate as it will work for image elements, link elements, dropdown boxes etc.

Therefore using moveToElement() method makes more sense to focus on any generic WebElement on the web page.

For an input box you will have to click() on the element to focus.

new Actions(driver).moveToElement(element).click().perform();

while for links and images the mouse will be over that particular element,you can decide to click() on it depending on what you want to do.

If the click() on an input tag does not work –

Since you want this function to be generic, you first check if the webElement is an input tag or not by –

   new Actions(driver).moveToElement(element).perform();


You can make similar changes based on your preferences.

Leave a Comment