Selenium + Java · Lesson 34 of 44

0/44 done

Module 34: Shadow DOM

34. Shadow DOM Elements & Selenium 4 getShadowRoot()

16 minlesson

Your task

Implement findElementInShadowRoot:

  1. Accept WebElement shadowHost and By cssLocator.
  2. Return shadowHost.getShadowRoot().findElement(cssLocator).

Write it in the editor, then press Check answer (Ctrl + Enter).

Automating Open Shadow DOM in Selenium 4

Standard XPath does not pierce Shadow DOM! You must locate the shadow host, obtain the SearchContext via getShadowRoot(), and locate inner elements via CSS selectors:

java
import org.openqa.selenium.SearchContext;

// 1. Locate shadow host element:
WebElement shadowHost = driver.findElement(By.cssSelector("#custom-dropdown-host"));

// 2. Get shadow root context:
SearchContext shadowRoot = shadowHost.getShadowRoot();

// 3. Find element inside shadow root using CSS:
WebElement internalBtn = shadowRoot.findElement(By.cssSelector("button.select-btn"));
internalBtn.click();

Key Takeaways & Walkthrough Summary

Web components encapsulate HTML and CSS inside Shadow DOM trees, hiding them from normal findElement queries. In Selenium 4, the getShadowRoot() method allows you to query elements inside open Shadow DOMs natively. Let's conquer Shadow DOM!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Can I use XPath inside a shadowRoot context?

No. The W3C specification restricts SearchContext on shadow roots to CSS selectors only (By.cssSelector).

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip