How do you tell if a checkbox is selected in Selenium for Java?


Check a checkbox is selected in Selenium for Java

Usually, there are 2 ways that we can use to check a checkbox (or radio button) is selected: 

First way: 

We can see whether a checkbox is checked or not using the asserted method present in selenium.

driver.findElement(By.id("locator")).isSelected()

In case, if you want to check a checkbox if it is not selected when you can use the below code.

if ( ! driver.findElement(locator).isSelected() )
{
     driver.findElement(locator).click();
}

Second way:

If you don't get the correct answer from the Evoque or then you can find the right attribute from the HTML code, then get the attribute.

if ( driver.findElement(locator).getAttribute("checked") == null)
{
     driver.findElement(locator).click();
}