About this lesson
isSelected in Selenium Java: read the state of checkboxes, radios and options
Selenium Java AssignmentsIntermediateElement States
How it works
isSelected() returns true for a checkbox that is ticked, a radio button that is chosen, or an option that is selected in a dropdown. Those are the only elements it is meant for. On any other element, such as a label, it returns false.
It reads the live state, not the HTML. On the Checkboxes page firstSelect5 loads with the checked attribute; untick it and isSelected() returns false straight away, even though the attribute in the source is unchanged.
Reading state without clicking is often all a test needs: checking that a saved preference loaded, or that a "select all" box ticked every row.
About the assignment
The Checkboxes page has one box that loads ticked and many that do not. You read the state of one of each without changing anything and print the results.
What you will do
- Find
firstSelect5andfirstSelect1by id. - Call
isSelected()on each without clicking. - Print one line per box in the order and format the task shows,
firstSelect5first.
Common mistakes
Using getAttribute("checked") with equals()
For an unticked box it returns
null, and callingequals()on that throwsNullPointerException.isSelected()always returns aboolean.Calling isSelected() on the label
A label is not selectable, so it always returns
false, whatever the box next to it shows.Reading the state too early
If the page ticks boxes with JavaScript after load, a check right after
get()can run first. Wait withExpectedConditions.elementToBeSelected()when state is set dynamically.
In a real test suite
State checks without clicks are common in settings and permission pages: load the page, read every checkbox, and compare the result with what the account should have.
Lesson 33 checked enabled state. Lesson 35 starts the waiting lessons, beginning with the implicit wait.
Related lessons
- Handle Checkboxes - Click and VerifyTick a box and watch
isSelected()change. - Handle Radio Buttons
isSelected()across a radio group. - Handle Multi-Select DropdownSelected options in a multi-select dropdown.
To try one of these calls on any page without a task, open the online Selenium compiler for Java.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/Checkboxes");
// TODO: Check isSelected() for firstSelect5 and firstSelect1
driver.quit();
}
}