0
0
Selenium Javatesting~15 mins

Checking state (isDisplayed, isEnabled, isSelected) in Selenium Java - Deep Dive

Choose your learning style9 modes available
Overview - Checking state (isDisplayed, isEnabled, isSelected)
What is it?
Checking state means verifying if a web element is visible, enabled, or selected on a webpage. In Selenium, methods like isDisplayed(), isEnabled(), and isSelected() help testers understand the current condition of elements before interacting with them. These checks prevent errors by ensuring actions happen only on elements ready for interaction. This helps create reliable automated tests.
Why it matters
Without checking element states, tests might try to click invisible buttons, type into disabled fields, or select already selected options, causing failures and unreliable results. This wastes time and hides real problems. Checking states ensures tests mimic real user behavior and catch issues early, improving software quality and user experience.
Where it fits
Before learning state checks, you should know basic Selenium commands to locate and interact with elements. After mastering state checks, you can learn advanced waits and conditions to handle dynamic web pages more reliably.
Mental Model
Core Idea
Before interacting with a web element, always verify if it is visible, enabled, and selected to avoid errors and mimic real user behavior.
Think of it like...
It's like checking if a door is unlocked, open, and the light inside is on before entering a room. If the door is locked (disabled), closed (not displayed), or already occupied (selected), you act differently.
┌───────────────┐
│ Web Element   │
├───────────────┤
│ isDisplayed() │──> Is element visible on screen?
│ isEnabled()   │──> Can user interact with it?
│ isSelected()  │──> Is element chosen/checked?
└───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding isDisplayed() method
🤔
Concept: Learn how to check if an element is visible on the page.
In Selenium Java, isDisplayed() returns true if the element is visible to the user. Invisible elements exist in the HTML but are hidden by CSS or not rendered. Example: WebElement button = driver.findElement(By.id("submit")); boolean visible = button.isDisplayed(); System.out.println("Button visible: " + visible);
Result
Prints true if the button is visible, false if hidden.
Understanding visibility prevents errors like clicking hidden elements that users cannot see or interact with.
2
FoundationUnderstanding isEnabled() method
🤔
Concept: Learn how to check if an element is enabled and ready for interaction.
isEnabled() returns true if the element is enabled, meaning the user can interact with it. Disabled elements are visible but grayed out or inactive. Example: WebElement input = driver.findElement(By.name("email")); boolean enabled = input.isEnabled(); System.out.println("Input enabled: " + enabled);
Result
Prints true if the input field is enabled, false if disabled.
Knowing if elements are enabled avoids trying to type or click on inactive controls, which would cause test failures.
3
IntermediateUnderstanding isSelected() method
🤔
Concept: Learn how to check if selectable elements like checkboxes or radio buttons are selected.
isSelected() returns true if the element is currently selected or checked. It applies to checkboxes, radio buttons, and options in dropdowns. Example: WebElement checkbox = driver.findElement(By.id("agreeTerms")); boolean selected = checkbox.isSelected(); System.out.println("Checkbox selected: " + selected);
Result
Prints true if the checkbox is checked, false if unchecked.
Checking selection state helps verify user choices and prevents redundant clicks or incorrect test assumptions.
4
IntermediateCombining state checks before actions
🤔Before reading on: do you think it's safe to click a button without checking if it's displayed and enabled? Commit to your answer.
Concept: Learn to combine isDisplayed() and isEnabled() to safely interact with elements.
Before clicking a button, verify it is visible and enabled: WebElement button = driver.findElement(By.id("submit")); if(button.isDisplayed() && button.isEnabled()) { button.click(); } else { System.out.println("Button not ready for click."); }
Result
Clicks the button only if it is visible and enabled; otherwise, prints a warning.
Combining checks mimics real user behavior and prevents exceptions caused by interacting with unavailable elements.
5
AdvancedHandling dynamic elements with state checks
🤔Before reading on: do you think isDisplayed() always returns true for elements present in the DOM? Commit to your answer.
Concept: Learn how dynamic web pages affect element states and how to handle them.
Elements may exist in the HTML but be hidden or disabled dynamically. Using explicit waits with ExpectedConditions can help: WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit"))); button.click();
Result
Waits until the button is visible and enabled before clicking, avoiding timing issues.
Understanding dynamic states and waits prevents flaky tests caused by timing and state changes.
6
ExpertLimitations and pitfalls of state methods
🤔Before reading on: do you think isDisplayed(), isEnabled(), and isSelected() always reflect the true user experience? Commit to your answer.
Concept: Explore edge cases and limitations of these methods in complex web apps.
Sometimes isDisplayed() returns true even if the element is off-screen or covered by another element. isEnabled() may not reflect custom disabled states controlled by JavaScript. isSelected() applies only to specific element types. Testers must combine these with other checks or JavaScript execution for accuracy.
Result
Recognizing these limits helps avoid false positives or negatives in tests.
Knowing method limitations guides testers to build more robust and realistic test validations.
Under the Hood
Selenium's isDisplayed() checks the element's CSS properties like display, visibility, and opacity to decide if it is visible. isEnabled() checks the HTML 'disabled' attribute or similar properties to determine if interaction is allowed. isSelected() checks the 'checked' or 'selected' attribute for applicable elements. These methods query the browser's DOM and rendering engine state at runtime.
Why designed this way?
These methods were designed to mimic how a real user perceives and interacts with elements, abstracting complex browser internals into simple boolean checks. Alternatives like manual JavaScript checks would be more complex and error-prone. The design balances simplicity and practical accuracy for automated testing.
┌─────────────────────────────┐
│ Selenium WebDriver          │
├─────────────┬───────────────┤
│ isDisplayed │ Checks CSS    │
│             │ display,      │
│             │ visibility    │
├─────────────┼───────────────┤
│ isEnabled   │ Checks HTML   │
│             │ disabled attr │
├─────────────┼───────────────┤
│ isSelected  │ Checks checked│
│             │ or selected   │
│             │ attributes    │
└─────────────┴───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does isDisplayed() return false if the element is off-screen but visible in the DOM? Commit to yes or no.
Common Belief:isDisplayed() returns false if the element is not visible anywhere on the page, including off-screen.
Tap to reveal reality
Reality:isDisplayed() returns true if the element is rendered and visible, even if it is off-screen or outside the viewport.
Why it matters:Tests may wrongly assume an element is invisible and skip actions, causing missed interactions or false test passes.
Quick: Does isEnabled() always reflect if a user can interact with an element? Commit to yes or no.
Common Belief:If isEnabled() returns true, the element is always interactable by the user.
Tap to reveal reality
Reality:isEnabled() only checks the HTML disabled attribute; JavaScript or CSS can still block interaction despite isEnabled() being true.
Why it matters:Tests may try to interact with elements that appear enabled but are blocked, causing unexpected failures.
Quick: Does isSelected() apply to all types of elements? Commit to yes or no.
Common Belief:isSelected() can be used to check selection state of any element.
Tap to reveal reality
Reality:isSelected() only works correctly on checkboxes, radio buttons, and options in select elements.
Why it matters:Using isSelected() on unsupported elements leads to incorrect test logic and false results.
Quick: Can you rely solely on isDisplayed(), isEnabled(), and isSelected() for all element state checks? Commit to yes or no.
Common Belief:These three methods cover all necessary element state checks for testing.
Tap to reveal reality
Reality:They cover common states but miss complex conditions like visibility behind overlays, partial disablement, or custom UI controls.
Why it matters:Overreliance causes flaky tests and missed bugs in modern web applications.
Expert Zone
1
Some elements may be visible but not interactable due to overlays or CSS pointer-events, which isDisplayed() does not detect.
2
isEnabled() does not detect custom disabled states controlled by JavaScript frameworks; testers may need to check attributes or styles manually.
3
isSelected() only applies to specific input types; for custom toggle controls, testers must use alternative checks.
When NOT to use
Avoid relying solely on these methods for complex or custom UI components. Instead, use explicit waits, JavaScript execution, or accessibility attributes to verify element states more accurately.
Production Patterns
In real-world tests, state checks are combined with waits and exception handling to build robust interactions. For example, waiting for elementToBeClickable combines visibility and enabled checks before clicking.
Connections
Explicit Waits in Selenium
Builds-on
Understanding element state checks is essential before using explicit waits that wait for those states, improving test stability.
User Experience (UX) Design
Related concept
Knowing how users perceive element states (visible, enabled, selected) helps testers write tests that reflect real user interactions.
Traffic Light System in Project Management
Analogous pattern
Just like red/yellow/green signals guide actions in projects, isDisplayed(), isEnabled(), and isSelected() guide test actions by signaling element readiness.
Common Pitfalls
#1Trying to click an element without checking if it is visible and enabled.
Wrong approach:WebElement button = driver.findElement(By.id("submit")); button.click();
Correct approach:WebElement button = driver.findElement(By.id("submit")); if(button.isDisplayed() && button.isEnabled()) { button.click(); } else { System.out.println("Button not ready for click."); }
Root cause:Assuming elements are always ready for interaction leads to exceptions or failed tests.
#2Using isSelected() on elements that are not checkboxes or radio buttons.
Wrong approach:WebElement div = driver.findElement(By.id("customToggle")); boolean selected = div.isSelected();
Correct approach:Use attribute or class checks for custom toggles, e.g., boolean selected = div.getAttribute("class").contains("active");
Root cause:Misunderstanding that isSelected() only applies to specific input types.
#3Assuming isEnabled() reflects all disabled states including JavaScript or CSS blocking interaction.
Wrong approach:WebElement input = driver.findElement(By.name("email")); if(input.isEnabled()) { input.sendKeys("test@example.com"); }
Correct approach:Check additional attributes or styles, e.g., boolean interactable = input.isEnabled() && !input.getAttribute("class").contains("readonly"); if(interactable) { input.sendKeys("test@example.com"); }
Root cause:Overreliance on isEnabled() without considering custom UI logic.
Key Takeaways
Checking element states with isDisplayed(), isEnabled(), and isSelected() ensures tests interact only with elements ready for user actions.
These methods help mimic real user behavior, preventing errors like clicking hidden or disabled elements.
Each method targets a specific aspect: visibility, interactivity, and selection, but they have limitations in complex web apps.
Combining state checks with waits and additional validations builds reliable, stable automated tests.
Understanding these checks deeply helps avoid common pitfalls and write tests that reflect true user experiences.