As I have mentioned in my previous articles, JavascriptExecutor is used for performing Javascript operations in a web browser from a selenium web driver.
To perform click operation on buttons/radio buttons/checkboxes/links using javascript, we have two ways,
- FindElement(Javascript) + Click (Javascript)
- FindElement(WebDriver) + Click (Javascript)
In both ways, performing click operation using javascript is common but finding an element is different.
In the first case, both finding an element and performing click operation use Javascript only.
In the second case, finding the element will be performed in the web driver and performing click operation will be performed in Javascript.
Now we will learn both of the ways here.
HTML Code snippet
- <div class='container'>
- <input type='radio' id='testRadio' />
- <input type='checkbox' id='city' />
- <button id='login'>Login</button>
- <a href='#'>Signup</a>
- </div>
To perform click operation using Javascript we need to use click method.
For buttons/radio buttons/checkboxes/links the default operation is click only.
Way1
In my previous article, we have already learned how to find the element using Javascript.
Now we use the click method to perform click operation on any button/radio button/checkbox/link.
Usage in Selenium code,
- String javascript = "document.getElementById('login').click()";
- JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
- jsExecutor.executeScript(javascript);
Way 2
I hope you already knew about "finding an element in the Selenium webdriver"; if not please follow the below article.
Now we use the click method to perform click operation on any button/radio button/checkbox/link
Usage in Selenium code,
- WebElement loginBtn = driver.findElement(By.id("login"));
- String javascript = "arguments[0].click()";
- JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
- jsExecutor.executeScript(javascript, loginBtn);
In way2, we are using arguments because we are finding the element outside javascript. So we are passing that element as an argument to Javascript.
So this is how we handle the buttons/radio buttons/checkboxes/links in javascript. You can choose any way (way1 or way2) based on your scenario.
If you are interested in watching all this information explained in a video, please watch
this video
In my next article, we will see how we can perform scroll operations.
I hope you find this article useful. Please provide your valuable feedback, questions, or comments about this article.