Correct way to focus an element in Selenium WebDriver using Java

questions picture questions · Jul 5, 2012 · Viewed 198.4k times · Source

What's the equivalent of selenium.focus() for WebDriver?

element.sendKeys("");

or

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

I have tried both of them and they worked, but which one would always work on all elements?

Which one is the correct way for any elements (such as button, link etc.)? This matters to me because the function will be used on different UI's.

Answer

Hari Reddy picture Hari Reddy · Jul 5, 2012

The following code -

element.sendKeys("");

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 -

if("input".equals(element.getTagName()){
   element.sendKeys("");
} 
else{
   new Actions(driver).moveToElement(element).perform();

}

You can make similar changes based on your preferences.