We check if elements are visible, clickable, or selected to make sure our tests interact with the right parts of a webpage.
Checking state (isDisplayed, isEnabled, isSelected) in Selenium Java
boolean isDisplayed = element.isDisplayed(); boolean isEnabled = element.isEnabled(); boolean isSelected = element.isSelected();
isDisplayed() returns true if the element is visible on the page.
isEnabled() returns true if the element can be interacted with (not disabled).
isSelected() returns true if the element is selected (applicable for checkboxes, radio buttons, and options).
WebElement button = driver.findElement(By.id("submitBtn"));
boolean visible = button.isDisplayed();WebElement checkbox = driver.findElement(By.name("agreeTerms"));
boolean selected = checkbox.isSelected();WebElement inputField = driver.findElement(By.cssSelector("input[type='text']"));
boolean enabled = inputField.isEnabled();This program opens a webpage, finds the submit button and terms checkbox, then prints if the button is visible and enabled, and if the checkbox is selected.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class CheckElementState { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/form"); WebElement submitButton = driver.findElement(By.id("submitBtn")); WebElement termsCheckbox = driver.findElement(By.id("terms")); boolean isSubmitVisible = submitButton.isDisplayed(); boolean isSubmitEnabled = submitButton.isEnabled(); boolean isTermsSelected = termsCheckbox.isSelected(); System.out.println("Submit button visible: " + isSubmitVisible); System.out.println("Submit button enabled: " + isSubmitEnabled); System.out.println("Terms checkbox selected: " + isTermsSelected); } finally { driver.quit(); } } }
Always check if an element is displayed before interacting to avoid errors.
isSelected() works mainly for checkboxes, radio buttons, and options in dropdowns.
Elements not enabled cannot be clicked or typed into.
Use isDisplayed() to check visibility.
Use isEnabled() to check if element can be used.
Use isSelected() to check selection state of checkboxes or radios.