docs.rodeo

MDN Web Docs mirror

Element: attachShadow() method

{{APIRef('Shadow DOM')}} 

The Element.attachShadow() method attaches a shadow DOM tree to the specified element and returns a reference to its {{domxref("ShadowRoot")}} .

Elements you can attach a shadow to

Note that you can’t attach a shadow root to every type of element. There are some that can’t have a shadow DOM for security reasons (for example {{htmlelement("a")}} ).

The following is a list of elements you can attach a shadow root to:

Calling this method on an element that is already a shadow host

The method may be called on an element that already has a declarative shadow root, provided the specified mode mode matches the existing mode. In this case the {{domxref("ShadowRoot")}}  that was already present will be cleared and returned. This allows for cases where, for example, server-side rendering has already declaratively created a shadow root, and then client-side code attempts to attach the root again.

Otherwise calling attachShadow() on an element that already has a shadow root will throw an exception.

Syntax

attachShadow(options)

Parameters

Return value

Returns a {{domxref("ShadowRoot")}}  object.

Exceptions

Examples

Word count custom element

The following example is taken from our word-count-web-component demo (see it live also). You can see that we use attachShadow() in the middle of the code to create a shadow root, which we then attach our custom element’s contents to.

// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    super();

    // count words in element's parent element
    const wcParent = this.parentNode;

    function countWords(node) {
      const text = node.innerText || node.textContent;
      return text
        .trim()
        .split(/\s+/g)
        .filter((a) => a.trim().length > 0).length;
    }

    const count = `Words: ${countWords(wcParent)}`;

    // Create a shadow root
    const shadow = this.attachShadow({ mode: "open" });

    // Create text node and add word count to it
    const text = document.createElement("span");
    text.textContent = count;

    // Append it to the shadow root
    shadow.appendChild(text);

    // Update count when element content changes
    this.parentNode.addEventListener("input", () => {
      text.textContent = `Words: ${countWords(wcParent)}`;
    });
  }
}

// Define the new element
customElements.define("word-count", WordCount, { extends: "p" });

Disabling shadow DOM

If the element has a static property named disabledFeatures, which is an array containing the string "shadow", then the attachShadow() call will throw an exception.

For example:

class MyCustomElement extends HTMLElement {
  // Disable shadow DOM for this element.
  static disabledFeatures = ["shadow"];

  constructor() {
    super();
  }

  connectedCallback() {
    // Create a shadow root.
    // This will throw an exception.
    const shadow = this.attachShadow({ mode: "open" });
  }
}

// Define the new element
customElements.define("my-custom-element", MyCustomElement);

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN