Back to All Scenarios
Scenario 10 of 100
Advanced
Advanced
Interacting with encapsulated Shadow DOM Elements
π€Scenario Overview
Interacting with encapsulated Shadow DOM Elements
Key Takeaways & Cheat Sheet
- βAccess Shadow DOM elements via Selenium 4 getShadowRoot() API
- βQuery inside shadow contexts strictly with CSS selectors (no XPath)
- βUse JavascriptExecutor script queries as a fallback compatibility method
- βTraverse multiple layers of nested shadow roots sequentially
Short Direct Answer
Shadow DOM encapsulates web component structures, isolating them from the main DOM document tree. Standard locators and XPath cannot see past this boundary. In Selenium 4, you can call getShadowRoot() on the shadow host element to obtain its SearchContext. From there, you can query inner child elements directly using CSS Selectors.
β οΈ Senior Warning (Red Flag)
Standard XPath expressions starting with // cannot pierce the Shadow DOM boundary. Trying to locate a shadow element with standard XPath will result in a NoSuchElementException every time.
π‘ STAR Deep Dive Explanation & Pro Tip
Always inspect the element in Chrome DevTools first. If you see "#shadow-root (open)", it means the element is encapsulated. Retrieve the parent "Shadow Host" element first, then use getShadowRoot() to find the internal target.
SeleniumAutomation.java
Selenium 4 + Javaimport org.openqa.selenium.SearchContext;
// β
Selenium 4: Accessing Shadow DOM directly
WebElement shadowHost = driver.findElement(By.cssSelector("theme-settings-panel"));
// Get the encapsulated search context
SearchContext shadowContext = shadowHost.getShadowRoot();
// Locate internal element inside the shadow root (CSS selector ONLY, XPath not supported)
WebElement darkModeToggle = shadowContext.findElement(By.cssSelector("button#dark-mode-toggle"));
darkModeToggle.click();
// β
Fallback: Access Shadow DOM via Javascript Executor (highly compatible)
WebElement toggleViaJS = (WebElement) ((JavascriptExecutor) driver).executeScript(
"return document.querySelector('theme-settings-panel').shadowRoot.querySelector('button#dark-mode-toggle')"
);
toggleViaJS.click();