How to find/target Shadow DOM

Find elements using CSS Selector which are inside the shadow root. XPATH will not work for Shadow DOM.

WebElement shaElementOne = driver.findElement(By.cssSelector(selector));
System.out.println("--"+shaElementOne.getTagName());
WebElement elementOne = (WebElement) ((JavascriptExecutor) driver).executeScript("return arguments[0].shadowRoot", shaElementOne);
Thread.sleep(1000);

String getText = elementOne.findElement(By.cssSelector(selector)).getText();
System.out.println("Print the Text:-" + getText);

Conclusion

We hope you guys have learned by reading this article.

Let us know if you have come across any other scenarios where you have found a better way to effectively implement this method. Also, if you have any questions, feel free to reach out to us via the comment section below.

:heart: Happy Testing :heart:

2 Likes