Script Fails with ElementNotVisibleException
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.
// β 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");