Click element using JavaScriptExecutor

In Selenium Webdriver, we can just use method to click on any element. But sometimes, when there are any issues performing click on any element, we can use JavaScriptExecutor.

Below is the example to perform click using JavaScriptExecutor.


import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class JSClickExample {
	WebDriver driver;

	public void testClickJS() throws Exception {
		driver = new FirefoxDriver();
		WebElement searchTextBox=driver.findElement("twotabsearchtextbox"));
		WebElement goButton = driver.findElement(By.cssSelector("input[value=Go]"));
	public void safeJavaScriptClick(WebElement element) throws Exception {
		try {
			if (element.isEnabled() && element.isDisplayed()) {
				System.out.println("Clicking on element with using java script click");

				((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
			} else {
				System.out.println("Unable to click on element");
		} catch (StaleElementReferenceException e) {
			System.out.println("Element is not attached to the page document "+ e.getStackTrace());
		} catch (NoSuchElementException e) {
			System.out.println("Element was not found in DOM "+ e.getStackTrace());
		} catch (Exception e) {
			System.out.println("Unable to click on element "+ e.getStackTrace());
Selenium Tutorials: 


How can we send Keyboard keys(Up/Down...etc) in javascript ?

This Magical code works for me , Can we have another code which wait after clicking an element

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.