Shadow DOM
Learn how to identify and interact with elements inside Shadow DOM using modern Selenium WebDriver techniques.
What You Will Practice
- Understand Shadow DOM.
- Identify a shadow host.
- Open a Shadow Root.
- Locate elements inside Shadow DOM.
- Interact with Shadow DOM inputs.
- Click Shadow DOM buttons.
- Work with nested Shadow DOM.
- Practice Selenium 4 ShadowRoot.
Shadow Host
Identify the element that contains the Shadow DOM.
WebElement host = driver.findElement(By.cssSelector("#user-profile-component"));
Open Shadow Root
Access the Shadow Root attached to the host element.
ShadowRoot shadowRoot = host.getShadowRoot();
Shadow DOM Input
Locate and enter text into an input inside Shadow DOM.
WebElement input = shadowRoot.findElement(By.cssSelector("#shadowUsername"));
input.sendKeys("Selenium User");
Shadow DOM Button
Locate and click a button inside Shadow DOM.
shadowRoot.findElement(By.cssSelector("#shadowClickTarget")).click();
Shadow DOM Text
Read text from an element located inside Shadow DOM.
String text = shadowRoot.findElement(By.cssSelector("#shadowMessage")).getText();
Nested Shadow DOM
Practice accessing a Shadow Root inside another Shadow Root.
ShadowRoot outerRoot = host.getShadowRoot();
ShadowRoot innerRoot = innerHost.getShadowRoot();
innerRoot.findElement(By.cssSelector("#nestedTarget"));
Complete Shadow DOM Challenge
Locate the employee name and click the action button inside the component.
ShadowRoot root = host.getShadowRoot();
WebElement employee = root.findElement(By.cssSelector("#shadowEmployeeName"));
WebElement action = root.findElement(By.cssSelector("#shadowEmployeeAction"));
action.click();
Shadow DOM Selenium Cheat Sheet
WebElement host =
driver.findElement(
By.cssSelector("#host")
);
ShadowRoot root =
host.getShadowRoot();
WebElement element =
root.findElement(
By.cssSelector("#element")
);
root.findElement(
By.cssSelector("#button")
).click();
root.findElement(
By.cssSelector("#input")
).sendKeys("Selenium");
String text =
root.findElement(
By.cssSelector("#message")
).getText();