Selenium + Java · Lesson 34 of 44
Module 34: Shadow DOM
Your task
Implement findElementInShadowRoot:
Write it in the editor, then press Check answer (Ctrl + Enter).
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:
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();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.
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.
___