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.
element.sendKeys("");
tries to find an input tag box to enter some information" ... This statement is definitely not true. ThesendKeys()
gets focus of the element (additionally, if that element isinput
, it takes cursor to the end of the already present text), then it presses keys (or simulates so) over the element. I think both approaches should work, themoveToElement()
is arguable cleaner and more readable, butsendKeys()
won't fail you, too. – Elizbeth