Bird
0
0

What is wrong with this code snippet that tries to check if a hidden element is visible?

medium📝 Debug Q7 of 15
Selenium Java - JavaScriptExecutor
What is wrong with this code snippet that tries to check if a hidden element is visible?
WebElement elem = driver.findElement(By.id("hidden"));
if(elem.isDisplayed()) {
  System.out.println("Visible");
} else {
  System.out.println("Not Visible");
}
ANo error, code works correctly
BShould use isEnabled() instead of isDisplayed()
CisDisplayed() cannot be used on hidden elements
DShould catch NoSuchElementException if element not found
Step-by-Step Solution
Solution:
  1. Step 1: Understand element presence vs visibility

    isDisplayed() works on elements present in DOM, even if hidden.
  2. Step 2: Identify missing exception handling

    If element is not present, findElement throws NoSuchElementException which is not handled here.
  3. Final Answer:

    Should catch NoSuchElementException if element not found -> Option D
  4. Quick Check:

    Handle NoSuchElementException when locating elements [OK]
Quick Trick: Always handle NoSuchElementException when locating elements [OK]
Common Mistakes:
  • Assuming isDisplayed() throws exception for hidden elements
  • Ignoring exceptions from findElement
  • Confusing isDisplayed() with isEnabled()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Selenium Java Quizzes