Element: shadowRoot property
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.
TheElement.shadowRoot
read-only propertyrepresents the shadow root hosted by the element.
UseElement.attachShadow()
to add a shadow root to an existing element.
Value
AShadowRoot
object instance, ornull
if the associatedshadow root was attached with itsmode
set toclosed
. (SeeElement.attachShadow()
for further details).
Some built-in elements, such as<input>
and<img>
, have user-agent shadow roots that are closed to script. Therefore, theirshadowRoot
property is alwaysnull
.
Examples
The following snippets are taken from ourlife-cycle-callbacksexample (see it live also), which creates an element that displays a square of a size and colorspecified in the element's attributes.
Inside the<custom-square>
element's class definition we includesome life cycle callbacks that make a call to an external function,updateStyle()
, which actually applies the size and color to the element.You'll see that we are passing itthis
(the custom element itself) as aparameter.
class Square extends HTMLElement { connectedCallback() { console.log("Custom square element added to page."); updateStyle(this); } attributeChangedCallback(name, oldValue, newValue) { console.log("Custom square element attributes changed."); updateStyle(this); }}
In theupdateStyle()
function itself, we get a reference to the shadow DOMusingElement.shadowRoot
. From here we use standard DOM traversaltechniques to find the<style>
element inside the shadow DOM and thenupdate the CSS found inside it:
function updateStyle(elem) { const shadow = elem.shadowRoot; const childNodes = Array.from(shadow.childNodes); childNodes.forEach((childNode) => { if (childNode.nodeName === "STYLE") { childNode.textContent = ` div { width: ${elem.getAttribute("l")}px; height: ${elem.getAttribute("l")}px; background-color: ${elem.getAttribute("c")}; } `; } });}
Specifications
Specification |
---|
DOM # ref-for-dom-element-shadowroot① |