Shadow DOM
Web components hide their insides in a shadow root. Some you can reach into; some you cannot.
Locating inside web components
Open shadow roots: nothing special to do
Playwright's role, text, label and CSS locators look inside open shadow roots automatically. You write the same locators as anywhere else:
// Two cards each have a Follow button, so scope to the card first.
const ada = page.locator('user-card').filter({ hasText: 'Ada Lovelace' });
await ada.getByRole('button', { name: 'Follow' }).click();
await expect(ada.getByRole('button', { name: 'Following' })).toBeVisible();XPath stops at the shadow boundary
XPath cannot see inside any shadow root. A locator that works in DevTools' Elements panel can still find nothing:
await expect(page.locator('xpath=//user-card//button')).toHaveCount(0);
await expect(page.locator('user-card button')).toHaveCount(2); // CSS worksSlotted content lives outside the shadow root
The "Mentor" badge is a normal child of <user-card>, projected into the card through a <slot>. It is in the light DOM, so every locator finds it, including XPath.
Closed shadow roots: work from the outside
A closed shadow root is hidden from scripts, Playwright included. The button inside the locked widget cannot be located at all. What you can use:
- the outer element's attributes, such as
data-state; - events and side effects outside it, such as the status line below;
- a mouse click at a position inside its bounding box.
const widget = page.locator('locked-widget');
await expect(widget.getByRole('button')).toHaveCount(0); // invisible to locators
await expect(widget).toHaveAttribute('data-state', 'locked');
const box = await widget.boundingBox();
await page.mouse.click(box!.x + box!.width / 2, box!.y + box!.height / 2);
await expect(widget).toHaveAttribute('data-state', 'unlocked');Closed shadow roots are rare. When an app uses one, ask the developers to expose state on the outer element or through events. Clicking by position is a last resort.
Open shadow root
Following: nobody
Closed shadow root
Widget state: locked
Next in Content & Attributes · 5 of 5Page Audit →Write automated checks that find every deliberate problem on this page.
Related exercises
- LocatorsIntermediateLocator ChallengesTarget exactly one element in each section without CSS selectors or test ids.
- Mouse & KeyboardIntermediateMouse ActionsUse the low-level mouse: modifier clicks, positions, drawing, the wheel and a slider.
- FramesBeginneriFrame BasicsEnter an iframe, work with the form inside it, and tell the frame element from its document.
Read the guide: Playwright locators: a practical guide with exercises