I want to check all unchecked checkboxes on this page: https://www.jquery-az.com/boots/demo.php?ex=63.0_2.
My current code loops through all checkboxes and clicks them if !isSelected(), but it ends up unchecking already checked boxes.
How can I modify the code to only select unchecked checkboxes without affecting the ones already checked?
This is the most straightforward approach. Only click checkboxes that are not selected:
List<WebElement> checkboxes = driver.findElements(By.cssSelector("input[type='checkbox']"));
for (WebElement checkbox : checkboxes) {
if (!checkbox.isSelected()) {
checkbox.click();
}
}
This ensures already checked boxes remain checked. To get started with Selenium Java, follow this blog on Selenium with Java and get detail insights on smooth Selenium automation.
If you prefer a more modern approach with streams:
driver.findElements(By.cssSelector("input[type='checkbox']"))
.stream()
.filter(cb -> !cb.isSelected())
.forEach(WebElement::click);
It does the same as the loop but is cleaner and expressive.
Sometimes, the page has checkboxes already checked by default with checked attribute. You can filter only those without it:
List<WebElement> unchecked = driver.findElements(
By.cssSelector("input[type='checkbox']:not(:checked)")
);
for (WebElement cb : unchecked) {
cb.click();
}
This uses a CSS pseudo-class to directly select unchecked checkboxes, so you don’t need to call isSelected().