About this lesson
isDisplayed in Selenium Java: check whether an element is visible
Selenium Java AssignmentsIntermediateElement States
How it works
isDisplayed() returns true if the element would be visible to a user. It returns false for an element hidden with visibility: hidden, with display: none, with opacity: 0, or inside a hidden parent. On Text Fields, invisibleField is in the DOM, so it can be found, but it is not displayed.
Being displayed is not the same as being on screen. An element further down the page, below the current viewport, still returns true. Visibility here is about CSS, not scrolling.
isDisplayed() needs an element first. If the element is not in the DOM at all, findElement() throws NoSuchElementException before isDisplayed() is ever called. To test "not present or not visible" safely, use findElements() and check the list.
About the assignment
Text Fields has ordinary inputs such as firstName and one input, invisibleField, styled visibility: hidden. You check isDisplayed() on each to see that both exist in the DOM but only one is visible.
What you will do
- Find the
firstNamefield and theinvisibleFieldfield by id. - Call
isDisplayed()on each. - Print one line per field in the order and format the task shows, field id first.
Common mistakes
Using isDisplayed() to check absence
For an element that is not in the DOM,
findElement()throwsNoSuchElementException, so thefalseyou expected never comes back.Reading the style attribute instead
Checking the inline
stylemisses hiding done by stylesheets and parent elements.isDisplayed()uses the computed result.Calling it in a loop to wait
Polling
isDisplayed()by hand withThread.sleep()is slow and flaky.ExpectedConditions.visibilityOfElementLocated()does this properly, as lesson 36 shows.
In a real test suite
Visibility checks back assertions such as "the error message appears after an invalid submit" or "the spinner is gone". Most of these are done through waits, which call the same visibility logic until it returns the answer you need.
Lesson 31 read a dropdown's choice. The next two lessons cover the other two state checks: isEnabled() and isSelected().
Related lessons
- Get CSS Value with getCssValue()The CSS properties that decide visibility, read one at a time.
- Explicit Wait - Element VisibleWait until an element becomes visible instead of checking once.
- Wait for an Element to DisappearWait until an element is no longer visible.
To try one of these calls on any page without a task, open the online Selenium compiler for Java.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/TextFields");
// TODO: Check isDisplayed() for firstName and invisibleField
driver.quit();
}
}