Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Element: shadowRoot property

BaselineWidely available

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.

js
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:

js
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①

Browser compatibility

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp