How to use JavaScript in selenium to click an Element?

How to use JavaScript in selenium to click an Element. I was using following code/html:

<button name="btnG" class="gbqfb" aria-label="Google Search" id="gbqfb"><span class="gbqfi"></span></button>
This is my Java code for clicking the element using selenium webdriver.


How can I implement this using Java Script and Webdriver?

Hi there,

Executing a click via JavaScript has some behaviors of which you should be aware. If, for example, the code bound to the on-click event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. However, in that, you can still use the WebDriver methods for locating the elements.

// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

You should also note that you might be better off using the click() method of the WebElementinterface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.