Correct Way to Focus an Element in Selenium Webdriver Using Java

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.

How to set focus on element on moving the mouse over it in Selenium WebDriver using Java?

I don't know why Actions class is not focusing the element. Its an issue or something as so many time i have trouble with Actions class in Firefox browser.

Still you have one alternative way to Focus on desired element and then perform click on focused element i.e. JavascriptExecutor

Here you is your code :

JavascriptExecutor jse = (JavascriptExecutor) driver;


Focus on an element Selenium





also, use proper variable names;

public void selectFilter(String filter) {
Iterator iter = elements.iterator();
if (iter.hasNext()) {
WebElement element = (WebElement);
if (element.getText().equals(filter))
new Actions(webDriver).moveToElement(element).perform();


getting cannot focus element in chrome and edge using java/selenium

sendkeys method is the problem as per the stack trace.

at org.openqa.selenium.remote.RemoteWebElement.sendKeys(

Please try Actions class to first focus on the element then send required keys.

Actions actions = new Actions(driver);
actions.sendKeys("SOME DATA");;

Related Topics

Leave a reply