How to retrieve all shadow roots of a web page

The only way to extract closed shadow roots defined with declarative shadow DOM

Marian C.
4 min readSep 5, 2024

Shadow DOM is a feature allowing isolation of a DOM tree together with its styles such that the elements in the shadow tree are not directly accessible from the outside of the host element. document.querySelectorAll() does not return any elements from a shadow tree. The elements inside a shadow tree can be accessed only from inside of the shadow tree starting from the shadow root of the tree.

A shadow root is a DocumentFragment. It can be either open or closed. When it is open, it can accessed through the shadowRoot property of the host element. When a shadow root is closed, the shadowRoot property of the host element is assigned null and, thus, the root cannot be recovered by external scripts without some trick.

There are two possible ways to create shadow DOM — with or without JavaScript.

Creating shadow DOM with attachShadow()

Until recently, the only possible way to define a shadow root was by calling attachShadow() method:

// attach.js

const shadowRoot = host.attachShadow({mode: 'closed'});
shadowRoot.innerHTML = '<h1>Header 2</h1>';

--

--

Marian C.
Marian C.

Written by Marian C.

Java, JavaScript and SQL developer. Interested in data collection and visualization.

Responses (15)