Detecting On‑Screen Element Visibility with Selenium WebDriver in Java
This guide explains how to determine whether a web element is visible on the screen during Selenium‑based Java automation, covering the basic isDisplayed() check, an enhanced visibility method that validates size, opacity and CSS visibility, strategies for dynamic, iframe and Shadow DOM elements, and practical best‑practice recommendations.
Introduction
In web automation testing, confirming that an element is displayed on the screen is a common and critical operation. This article details how to achieve this using Java together with Selenium WebDriver, providing flowcharts and code examples to aid understanding.
Basic Concept of Element Visibility
In web automation, "element visibility" typically requires two conditions simultaneously:
The element exists in the DOM.
The element is visible on the page (not hidden and has actual width and height).
Detection Flow
Java Implementation
1. Using Selenium's isDisplayed() method
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ElementVisibilityCheck {
public static void main(String[] args) {
// Set WebDriver path
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
// Check if element is displayed
boolean isDisplayed = isElementDisplayed(driver, By.id("elementId"));
System.out.println("Element displayed: " + isDisplayed);
} finally {
driver.quit();
}
}
/**
* Check if element is displayed
* @param driver WebDriver instance
* @param by Locator
* @return true if element exists and is visible, false otherwise
*/
public static boolean isElementDisplayed(WebDriver driver, By by) {
try {
WebElement element = driver.findElement(by);
return element.isDisplayed();
} catch (org.openqa.selenium.NoSuchElementException e) {
return false;
}
}
}2. Enhanced visibility check
public static boolean isElementReallyDisplayed(WebDriver driver, By by) {
try {
WebElement element = driver.findElement(by);
// Check visibility flag
if (!element.isDisplayed()) {
return false;
}
// Check size
if (element.getSize().getHeight() <= 0 || element.getSize().getWidth() <= 0) {
return false;
}
// Check opacity
String opacity = element.getCssValue("opacity");
if (opacity != null && !opacity.isEmpty() && Double.parseDouble(opacity) <= 0) {
return false;
}
// Check CSS visibility property
String visibility = element.getCssValue("visibility");
if ("hidden".equals(visibility)) {
return false;
}
return true;
} catch (org.openqa.selenium.NoSuchElementException e) {
return false;
}
}Handling Dynamic Elements
For elements that load asynchronously, an explicit wait using FluentWait can be employed:
import org.openqa.selenium.support.ui.FluentWait;
import java.time.Duration;
import java.util.function.Function;
public static boolean waitForElementDisplayed(WebDriver driver, By by, long timeoutSeconds) {
FluentWait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(timeoutSeconds))
.pollingEvery(Duration.ofMillis(500))
.ignoring(org.openqa.selenium.NoSuchElementException.class);
try {
return wait.until(new Function<WebDriver, Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
WebElement element = driver.findElement(by);
return element != null && element.isDisplayed();
}
});
} catch (org.openqa.selenium.TimeoutException e) {
return false;
}
}Common Issues and Solutions
Element outside viewport – use JavaScript to verify visibility within the visible area
public static boolean isElementInViewport(WebDriver driver, WebElement element) {
return (Boolean) ((JavascriptExecutor) driver).executeScript(
"var rect = arguments[0].getBoundingClientRect();" +
"return (rect.top >= 0 && rect.left >= 0 && " +
"rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && " +
"rect.right <= (window.innerWidth || document.documentElement.clientWidth));",
element);
}Element inside an iframe – switch to the appropriate iframe first
driver.switchTo().frame("frameNameOrId");
// perform checks
driver.switchTo().defaultContent(); // back to main documentShadow DOM element – access via JavaScript execution
public static WebElement getShadowDOMElement(WebDriver driver, WebElement shadowHost, String selector) {
return (WebElement) ((JavascriptExecutor) driver).executeScript(
"return arguments[0].shadowRoot.querySelector(arguments[1]);",
shadowHost, selector);
}Best Practices
Always verify element existence before checking visibility.
For dynamically loaded elements, prefer explicit waits over fixed sleeps.
Consider all visibility factors: size, opacity, and CSS visibility property.
Use JavaScript for precise checks in complex scenarios such as iframes or Shadow DOM.
Encapsulate common checks into reusable utility methods.
Conclusion
Accurately determining whether an element is displayed is essential for reliable web automation tests. By applying the methods and best practices described above, testers can build more robust test cases that handle a wide range of visibility scenarios, selecting the appropriate technique based on project needs and combining multiple approaches when necessary.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Woodpecker Software Testing
The Woodpecker Software Testing public account shares software testing knowledge, connects testing enthusiasts, founded by Gu Xiang, website: www.3testing.com. Author of five books, including "Mastering JMeter Through Case Studies".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
