How to Check if Element is Selected in Selenium
In Selenium, you can check if an element is selected by using the
isSelected() method on a WebElement. This method returns true if the element (like a checkbox or radio button) is selected, otherwise false. Use it after locating the element with a proper locator.Syntax
The isSelected() method is called on a WebElement object to check if it is selected.
WebElement: The element you want to check (e.g., checkbox, radio button).isSelected(): Returnstrueif the element is selected,falseotherwise.
java
boolean isSelected = element.isSelected();Example
This example shows how to open a webpage, locate a checkbox, check if it is selected, and print the result.
java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class CheckSelectedExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://www.w3schools.com/howto/howto_css_custom_checkbox.asp"); // Locate the first checkbox WebElement checkbox = driver.findElement(By.xpath("(//input[@type='checkbox'])[1]")); // Check if checkbox is selected boolean selected = checkbox.isSelected(); System.out.println("Checkbox selected? " + selected); } finally { driver.quit(); } } }
Output
Checkbox selected? false
Common Pitfalls
- Using
isSelected()on elements that are not selectable (likedivorspan) will always returnfalse. - Not waiting for the element to be present or visible before calling
isSelected()can causeNoSuchElementException. - Confusing
isSelected()withisDisplayed()orisEnabled(). They check different states.
java
/* Wrong: Using isSelected() on a non-selectable element */ WebElement divElement = driver.findElement(By.id("someDiv")); boolean selected = divElement.isSelected(); // Always false /* Right: Use isSelected() only on checkboxes, radio buttons, or options */ WebElement checkbox = driver.findElement(By.id("checkboxId")); boolean selectedCorrect = checkbox.isSelected();
Quick Reference
Remember these key points when checking if an element is selected in Selenium:
- Use
isSelected()only on selectable elements like checkboxes, radio buttons, and options. - Always locate the element correctly before checking.
- Handle exceptions by waiting for elements to be ready.
isSelected()returns a booleantrueorfalse.
Key Takeaways
Use the isSelected() method on WebElement to check selection state.
Only use isSelected() on elements that can be selected like checkboxes or radio buttons.
Ensure the element is present and visible before calling isSelected() to avoid errors.
isSelected() returns true if selected, false otherwise.
Do not confuse isSelected() with isDisplayed() or isEnabled().