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

I am using Selenium in Java to test the checking of a checkbox in a webapp. Here's the code:

private boolean isChecked;
private WebElement e;

I declare e and assign it to the area where the checkbox is.

isChecked = e.findElement(By.tagName("input")).getAttribute("checked").equals("true");

What is weird is that getAttribute("checked") returns null and therefore a NullPointerException

In the HTML for the checkbox, there is no checked attribute displayed. However, isn't it the case that all input elements have a checked = "true" so this code should work?

This question is related to java selenium attributes checkbox nullpointerexception

The answer is


For the event where there are multiple check-boxes from which you'd like to select/deselect only a few, the following work with the Chrome Driver (somehow failed for IE Driver):

NOTE: My check-boxes didn't have an ID associated with them, which would be the best way to identify them according to the Documentation. Note the ! sign at the beginning of the statement.

if(!driver.findElement(By.xpath("//input[@type='checkbox' and @name='<name>']")).isSelected()) 
{
  driver.findElement(By.xpath("//input[@type='checkbox' and @name= '<name>']")).click();
}

I would do it with cssSelector:

// for all checked checkboxes
driver.findElements(By.cssSelector("input:checked[type='checkbox']"));
// for all notchecked checkboxes
driver.findElements(By.cssSelector("input:not(:checked)[type='checkbox']"));

Maybe that also helps ;-)


  1. Declare a variable.
  2. Store the checked property for the radio button.
  3. Have a if condition.

Lets assume

private string isChecked; 
private webElement e; 
isChecked =e.findElement(By.tagName("input")).getAttribute("checked");
if(isChecked=="true")
{

}
else 
{

}

Hope this answer will be help for you. Let me know, if have any clarification in CSharp Selenium web driver.


The mechanism of selenium framework:

Here selenium make request to the its server and fetch first subelement with tagname input

WebElement e = e.findElement(By.tagName("input"));

Than you try to receive attribute on that element

object attribute = e.getAttribute("checked")

So either use

findElement(By.attribute("checked")

or use

findElement(By.xpath("\\input[@checked='true']")

P.S. I'm not familiar with java's equivalent of selenium api so some method may be named slightly different.


public boolean getcheckboxvalue(String element)
    {   
        WebElement webElement=driver.findElement(By.xpath(element));
        return webElement.isSelected();
    }

 if(checkBox.getAttribute("checked") != null) // if Checked 
    checkBox.click();                         //to Uncheck it 

You can also add an and statement to be sure if checked is true.


if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
     driver.findElement(By.id("idOfTheElement")).click();
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to attributes

Get the name of a pandas DataFrame What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag? AttributeError: can't set attribute in python How can I disable selected attribute from select2() dropdown Jquery? How do I pass multiple attributes into an Angular.js attribute directive? AngularJS - Attribute directive input value change Are complex expressions possible in ng-hide / ng-show? Get all attributes of an element using jQuery Removing html5 required attribute with jQuery Set attribute without value

Examples related to checkbox

Setting default checkbox value in Objective-C? Checkbox angular material checked by default Customize Bootstrap checkboxes Angular ReactiveForms: Producing an array of checkbox values? JQuery: if div is visible Angular 2 Checkbox Two Way Data Binding Launch an event when checking a checkbox in Angular2 Checkbox value true/false Angular 2: Get Values of Multiple Checked Checkboxes How to change the background color on a input checkbox with css?

Examples related to nullpointerexception

Filter values only if not null using lambda in Java8 Why use Optional.of over Optional.ofNullable? Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference Null pointer Exception on .setOnClickListener - java.lang.NullPointerException - setText on null object reference NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference Java 8 NullPointerException in Collectors.toMap NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0