Shadow DOM

What Is a Shadow DOM

Web components hide their inner HTML inside a shadow root. Normal CSS selectors and XPath from the page cannot see inside it, so findElement fails even though the element is visible.

<shopease-coupon-box id="coupon-box">
  #shadow-root (open)
    <input class="coupon-input" placeholder="Enter coupon">
    <button class="apply">Apply</button>
</shopease-coupon-box>

Example

Searching directly:

Run CouponTest.main()

Example output

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".coupon-input"}

getShadowRoot

SearchContext shadow = driver.findElement(By.id("coupon-box")).getShadowRoot();   // Selenium 4
shadow.findElement(By.cssSelector(".coupon-input")).sendKeys("FESTIVE10");
shadow.findElement(By.cssSelector(".apply")).click();
System.out.println(driver.findElement(By.id("discount")).getText());

Example

Output:

Run CouponTest.main()

Example output

Discount (FESTIVE10): -₹129.90

Note: Inside a shadow root use CSS selectors only; XPath is not supported there. For nested components call getShadowRoot() again on the inner host element. A closed shadow root cannot be accessed at all; ask developers for a test hook.