How can I ensure that only unchecked checkboxes are selected in Selenium Java?

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();
    }
}

:white_check_mark: 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().

You’re on the right track — you just need to check the box’s state before clicking it. Instead of toggling every checkbox, make your code target only unchecked ones. For example, in JavaScript:

document.querySelectorAll('input[type="checkbox"]').forEach(cb => {
  if (!cb.checked) cb.click();
});

This way, it only clicks unchecked boxes and leaves the checked ones untouched.