> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/component/shadow-dom/shadow-root.md).

# shadow root vs. host

{% tabs %}
{% tab title="📘 手冊" %}

* [Element.shadowRoot](https://developer.mozilla.org/en-US/docs/Web/API/Element/shadowRoot)
* [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) ⟩ [Node](https://developer.mozilla.org/en-US/docs/Web/API/Node) ⟩ [DocumentFragment](https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment) ⟩ [ShadowRoot](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot) :star:&#x20;
* Google ⟩ [Creating shadow DOM](https://developers.google.com/web/fundamentals/web-components/shadowdom#create)
  {% endtab %}

{% tab title="🛠 工具" %}

* web platform test: [ShadowRoot](http://wpt.live/shadow-dom/ShadowRoot-interface.html)
  {% endtab %}
  {% endtabs %}

{% hint style="info" %}
The [**attachShadow**](https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow)() method receives a **mode** that can be '**open**' or '**closed**'. \
:point\_right:[parameters](https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow#parameters) for `element.attachShadow()`.&#x20;

* '**open**':  **can access** the **Shadow DOM** ([`elem.shadowRoot`](https://developer.mozilla.org/en-US/docs/Web/API/Element/shadowRoot)) from the **main context**.&#x20;
* '**closed**': you **can’t**. (`elem.shadowRoot == null`)
  {% endhint %}

```javascript
// attach a shadow DOM to element
let root = host.attachShadow({mode: 'open'});
// ⭐️ root.host === host
// ⭐️ host.shadowRoot === root
```

{% hint style="warning" %}

* The **shadow host** must be either a **custom element**, or one of: “**article**”, “**aside**”, “**blockquote**”, “**body**”, “**div**”, “**footer**”, “**h1**…**h6**”, “**header**”, “**main**” “**nav**”, “**p**”, “**section**”, or “**span**”.
* The spec [defines a list of elements](https://dom.spec.whatwg.org/#dom-element-attachshadow) that **can't host** a shadow tree.
  {% endhint %}
