Check if Web Element is Displayed
To check if specific web element is displayed using Selenium for Java, call isDisplayed()
method on the Web Element object. isDisplayed()
method returns true is the Web Element is displayed, else it returns false.
The following is a simple code snippet to if the web element element
is displayed.
</>
Copy
element.isDisplayed();
where element
is the WebElement object.
Example
In the following program, we write Selenium Java code to visit Tutorialkart Home Page, and check if the Java tutorial link is displayed.
Java Program
</>
Copy
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class MyAppTest {
public static void main(String[] args) {
//initialize web driver
System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
WebDriver driver = new ChromeDriver();
try {
driver.get("https://www.tutorialkart.com/");
//click on Java link
WebElement tutorialLink = driver.findElement(By.xpath("//a[@href=\"/java/\"]"));
//check if Java link is displayed
boolean isTutorialLinkDisplayed = tutorialLink.isDisplayed();
if (isTutorialLinkDisplayed) {
System.out.println("The link is displayed.");
} else {
System.out.println("The link is not displayed.");
}
} finally {
driver.quit();
}
}
}
Output
The link is displayed.