How to Click in Selenium webdriver using JavaScript

Do you know we can also Click in Selenium webdriver using JavaScript using different approaches. I have covered previously as well like How to perform click operation in Selenium Webdriver but now we are going to talk about something new I mean how to click in Selenium webdriver using JavaScript for an element which is disabled.

While working with disabled web element you will get Illegal State exception which might be new for you. You can easily come out using JAVAScript. This is one of the most important questions in Interviews as well.

If you are completely new to JavaScript then I would highly recommend you to visit JavaScript in Selenium and Different usage.

Click in Selenium webdriver using JavaScript

 

Overview

Let me tell you what exactly you will learn today and why I am covering this.

I had one scenario where some element was invisible and the requirement was I had to click on that elements. As we know Selenium does not that capability that it can change the visibility of Element.

JavaScript is much powerful which takes the complete access of DOM, so using JavaScript we can make any element visible forcefully.

Finally, I completed my script using JavaScript and performed all the required operation.

 

Approach for – How to click in Selenium webdriver using JavaScript.

 

If the element is invisible and if you try to click on any operation then it will throw Element Not visible exception which will fail your script. You can handle this exception using try catch approach as well but we have another approach using JavaScript.

  1. First, we will identify what exception is coming from the script.
  2. If an exception is related to disable or visibility then we can create the object of JavaScriptExecutor.
  3. Use Selenium code to perform or execute JavaScript code.

 

We can execute any JavaScript using JavaScriptExecutor interface in Selenium. It has a method called executeScript which will perform our task.

If you are new in Java then check Java topics for Selenium which will help you to understand Selenium easily.

 

Program click in Selenium webdriver using JavaScript

 

This is one of the shortest posts but it is useful when you get stuck with some scenario. Let me know your thoughts on this in below comment section.

 

For More updates Learn Automation page

For any query join Selenium group- Selenium Group

2 Comments

  1. Mohammed Fareed