How do I interact with elements inside a shadow DOM using Playwright?


To interact with elements inside a shadow DOM using Playwright, follow these steps:

  1. Locate the parent element with a shadow root using a selector method like page.$.
  2. Call the shadowRoot() method on the parent element to get a reference to the shadow root.
  3. Use standard DOM methods like querySelector or querySelectorAll on the shadow root to find and interact with elements inside it.

Here's an example using TypeScript and @playwright/test:

import { test, expect } from '@playwright/test';

test('interact with shadow DOM elements', async ({ page }) => {
  await page.goto('https://ray.run/');

  // Find an element with a shadow root
  const parentElement = await page.$('#my-element');

  // Get a reference to the shadow root
  const shadowRoot = await parentElement.shadowRoot();

  // Find an element inside the shadow root
  const childElement = await shadowRoot.$('#my-child-element');

  // Interact with the child element
  await childElement.click();

In this example, you first find the parent element with ID "my-element" using page.$. Then, you call its shadowRoot() method to get a reference to its associated Shadow Root object. Finally, you use $ again on the Shadow Root object to find an inner child element with ID "my-child-element" and click it.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.