How to Check if Element is Displayed in Selenium
In Selenium, use the
isDisplayed() method on a web element to check if it is visible on the page. This method returns true if the element is shown and false if it is hidden or not present.Syntax
The isDisplayed() method is called on a WebElement object. It returns a boolean indicating if the element is visible on the page.
- WebElement: The element you want to check.
- isDisplayed(): Returns
trueif visible,falseotherwise.
java
boolean visible = driver.findElement(By.id("elementId")).isDisplayed();
Example
This example shows how to open a webpage, find an element by its ID, and check if it is displayed. It prints the result to the console.
java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class CheckElementDisplayed { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com"); WebElement element = driver.findElement(By.id("exampleElement")); boolean isVisible = element.isDisplayed(); System.out.println("Element displayed: " + isVisible); } catch (Exception e) { System.out.println("Element not found or not displayed."); } finally { driver.quit(); } } }
Output
Element displayed: true
Common Pitfalls
Common mistakes when checking if an element is displayed include:
- Trying to call
isDisplayed()on an element that does not exist, which throwsNoSuchElementException. - Confusing
isDisplayed()withisEnabled()orisSelected(), which check different states. - Not handling exceptions when the element is missing, causing test failures.
To avoid errors, first check if the element exists or handle exceptions properly.
java
import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.NoSuchElementException; try { WebElement element = driver.findElement(By.id("missingElement")); boolean visible = element.isDisplayed(); System.out.println("Visible: " + visible); } catch (NoSuchElementException e) { System.out.println("Element not found."); }
Output
Element not found.
Quick Reference
| Method | Purpose | Returns |
|---|---|---|
| isDisplayed() | Checks if element is visible on page | boolean (true/false) |
| isEnabled() | Checks if element is enabled (can be interacted with) | boolean (true/false) |
| isSelected() | Checks if element (checkbox/radio) is selected | boolean (true/false) |
Key Takeaways
Use isDisplayed() on a WebElement to check if it is visible on the page.
Handle exceptions like NoSuchElementException to avoid test failures when element is missing.
isDisplayed() returns false if the element is hidden but present in the DOM.
Do not confuse isDisplayed() with isEnabled() or isSelected(), they check different states.