Click the last but one checkbox



  • 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?



  • 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.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2