πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 11 of 100
Exceptions
Intermediate

Script Fails with ElementNotVisibleException

πŸ‘οΈScenario Overview

Script Fails with ElementNotVisibleException

Key Takeaways & Cheat Sheet

  • βœ“Understand that the element exists in DOM but has 0 width, height, or display: none
  • βœ“Verify viewport coordinates or check if parent container is collapsed
  • βœ“Wait explicitly for ExpectedConditions.visibilityOf(element) before interaction
  • βœ“Avoid attempting interaction with hidden fallback fields (e.g. file upload inputs)

Short Direct Answer

ElementNotVisibleException occurs when an element is present in the HTML DOM but is hidden from the rendered page (e.g., hidden via CSS styles like `display:none` or `visibility:hidden`, or hidden behind another element). To resolve this, always wait explicitly for the element to become visible, or ensure that you are targeting the correct interactive UI node rather than a hidden background element.

⚠️ Senior Warning (Red Flag)

Do not use driver.findElement() and immediately interact without checking visibility. An element present in the DOM is not guaranteed to be render-visible to the user, leading to immediate ElementNotVisibleException.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

If the element is hidden behind a collapsed menu, you must perform the necessary preparatory actions (like clicking the menu toggle) to render it visible in the DOM before attempting interaction.

SeleniumAutomation.java
Selenium 4 + Java
// ❌ Brittle: driver.findElement(By.id("username")).sendKeys("testUser");
// If username is in DOM but hidden inside a collapsed drawer, it will throw ElementNotVisibleException.

// βœ… Wait for visibility of element before interaction
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement visibleElement = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.id("username-display"))
);
visibleElement.sendKeys("testUser");