How to focus object in selenium web driver?

HTMLElement.focus()

The HTMLElement.focus() method sets focus on the desired element, if it can be focused. The focused element is the element which can receive the keyboard and similar events by default.


This usecase

Generally, invoking click() will set the focus on the desired element.

driver.findElement(By.cssSelector("element_cssSelector")).click();

Ideally, you should induce WebDriverWait for the elementToBeClickable() while invoking the click() to set the focus as follows:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("element_cssSelector"))).click();

At times, you may need to use moveToElement() method from Actions Class inconjunction with click() to set the focus as follows:

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

You can also use the executeScript() method from JavascriptExecutor Interface to set the focus as follows:

((JavascriptExecutor)driver).executeScript("document.getElementById('element_ID').focus();");

But in this case, you need to ensure that the specific window is focused and to achive that you can use the following line of code:

((JavascriptExecutor)driver).executeScript("window.focus();");

Leave a Comment