Have a question?
Message sent Close
View Categories

How to handle basic functionality using JavaScriptExecutor?

📄
filename.js
WebElement textBox = driver.findElement(By.id("username"));

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("arguments[0].value='VinothQA';", textBox);

📄
filename.js
WebElement checkbox = driver.findElement(By.id("acceptTerms"));

js.executeScript("arguments[0].checked=true;", checkbox);

📄
filename.js
js.executeScript("arguments[0].checked=false;", checkbox);

📄
filename.js
js.executeScript("arguments[0].click();", checkbox);
📄
filename.js
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);

📄
filename.js
WebElement dropdown = driver.findElement(By.id("country"));

js.executeScript("arguments[0].value='IN';", dropdown); // Set value attribute

📄
filename.js
js.executeScript("arguments[0].value='IN'; arguments[0].dispatchEvent(new Event('change'));", dropdown);

📄
filename.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);

📄
filename.js
WebElement button = driver.findElement(By.id("submitBtn"));

js.executeScript("arguments[0].click();", button);