Check if Element is Displayed

To check if specified web element is displayed or not, programmatically, using Selenium in Java, use WebElement.isDisplayed() function.

We first find the web element by name, id, class name, etc., and then call the isDisplayed() function on this web element. isDisplayed() function returns a boolean value of true if the web element is displayed, or false if the web element is hidden.

The following is a simple code snippet where we find the a web element with the name q and then check if this element is displayed or not.

</>
Copy
WebElement searchBox = driver.findElement(By.name("q"));
Boolean isSearchBoxDisplayed = searchBox.isDisplayed();

Example

In the following program, we write Java code to find the web element (name=”q”), check if it is displayed or not using isDisplayed() function.

Java Program

</>
Copy
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.time.Duration;

public class MyAppTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");  
    	WebDriver driver = new ChromeDriver();
        driver.get("https://google.com/ncr");
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));

        WebElement searchBox = driver.findElement(By.name("q"));
        Boolean isSearchBoxDisplayed = searchBox.isDisplayed();
        
        if (isSearchBoxDisplayed) {
        	System.out.println("The search box is displayed.");
        } else {
        	System.out.println("The search box is not displayed.");
        }
        
        driver.quit();
    }
}

Output

The search box is displayed.