This article will discuss performing click operations on buttons, radio buttons, checkboxes, and links using Javascript.
In my previous articles, I have explained about JavascriptExecutor and covered the below points.
As I have mentioned in my previous articles, JavascriptExecutor is used for performing Javascript operations in a web browser from a Selenium web driver.
In the Selenium web driver we know the syntax to perform click operations,
driver.findElement(By.id("<<id>>")).click();
Here is Javascript the syntax is quite different than the Selenium web driver, but the method name is the same as the Selenium web driver i.e: click.
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 operations 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 the 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 the 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.
Overview of Selenium Locators
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.
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.