1

In a page there are n number of checkboxes. Each time the page refreshes the list of checkboxes will also be refreshed and can be a different size. How do I click the second last (last but one) checkbox every time?

1 Answer 1

3

Locate all checkboxes i.e.:

List<WebElements> checkboxes = driver.findElements(By...)

Now, for a 0-based list, the last element will be checkboxes.size()-1, so what we want to do is:

if (checkboxes.size() > 0) {
        if (checkboxes.size() > 1) {
            checkboxes.get(checkboxes.size() - 2).click();
        } else {
            //either select the last and only checkbox or throw an error
        }
    } else {
        //handle the error as list was empty
    }

As this will select the second last element.

2
  • I would suggest checkboxes.size() == 0 || checkboxes.size() == 1, so you don't have to have nested conditions. May 9, 2019 at 22:38
  • It would even br enough to check if the list is bigger then 1, but we do not know if a single checkbox scenario is a valid case, hence the nested if.
    – Moro
    May 10, 2019 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.