How to handle basic functionality
using JavaScriptExecutor?
We can use JavaScriptExecutor in Selenium to interact with elements such as text boxes, checkboxes, radio buttons, dropdowns, and buttons, especially when standard Selenium methods (.click(), .sendKeys(), etc.) do not work due to JavaScript frameworks, hidden elements, or overlays.
Below are JavaScriptExecutor code examples for each type in Java:
1. Text Box: Set Value
WebElement textBox = driver.findElement(By.id("username"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].value='VinothQA';", textBox);
2. Checkbox: Check/Uncheck
Check the Checkbox
WebElement checkbox = driver.findElement(By.id("acceptTerms"));
js.executeScript("arguments[0].checked=true;", checkbox);
Uncheck the Checkbox
js.executeScript("arguments[0].checked=false;", checkbox);
Or Click (simulates user click via JS)
js.executeScript("arguments[0].click();", checkbox);
3. Radio Button: Select
WebElement radioBtn = driver.findElement(By.id("genderMale"));
js.executeScript("arguments[0].checked=true;", radioBtn);
// Or to simulate a user click:
js.executeScript("arguments[0].click();", radioBtn);
4. Dropdown (Select): Set Value
For a simple <select> element:
WebElement dropdown = driver.findElement(By.id("country"));
js.executeScript("arguments[0].value='IN';", dropdown); // Set value attribute
If you want to trigger events (like change), do:
js.executeScript("arguments[0].value='IN'; arguments[0].dispatchEvent(new Event('change'));", dropdown);
For custom dropdowns:
Click to open and select an option using JS:
// Example: click the dropdown
js.executeScript("arguments[0].click();", dropdown);
// Then click the desired option (locate it first)
WebElement option = driver.findElement(By.xpath("//li[text()='India']"));
js.executeScript("arguments[0].click();", option);
5. Button: Click
WebElement button = driver.findElement(By.id("submitBtn"));
js.executeScript("arguments[0].click();", button);
Summary Table
Element | JavaScriptExecutor Example |
Text box | arguments[0].value=’text’; |
Checkbox | arguments[0].checked=true; or .click(); |
Radio | arguments[0].checked=true; or .click(); |
Dropdown | arguments[0].value=’value’; + dispatchEvent(new Event(‘change’)); |
Button | arguments[0].click(); |
Tips:
- Always pass the element as an argument (see arguments[0]).
- For dropdowns, ensure you match the correct value or text.
Use dispatchEvent(new Event(‘change’)) to trigger change handlers after setting values programmatically.