Skip to content

Clicking Elements in Selenium using JavaScript

Ha Do edited this page Oct 27, 2020 · 1 revision

Selenium comes with a handy WebElement#click method that invokes a click event on a given element. But in some cases click action is not possible.

One example is if we want to click a disabled element. In that case, WebElement#click throws an IllegalStateException. Instead, we can use Selenium's JavaScript support.

To do this, the first thing that we'll need is the JavascriptExecutor. Since we are using the ChromeDriver implementation, we can simply cast it to what we need:

JavascriptExecutor executor = (JavascriptExecutor) driver;

After getting the JavascriptExecutor, we can use its executeScript method. The arguments are the script itself and an array of script parameters. In our case, we invoke the click method on the first argument:

executor.executeScript("arguments[0].click();", element);

Now, lets put it together into a single method that we'll call clickElement:

private void clickElement(WebElement element) {
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    executor.executeScript("arguments[0].click();", element);
}

usage:

WebElement seeSearchResultsButton = driver.findElement(By.cssSelector(".btn-search"));
clickElement(seeSearchResultsButton);