dom_dom0700_010

カスタム要素でテンプレートを複製して Shadow DOM に配置する実装として最も適切なのはどれか。

[ html ]

<template id="tpl">
  <style>.box{border:1px solid #ccc;padding:4px}</style>
  <div class="box"><slot></slot></div>
</template>
<my-box>Content</my-box>
  1. const n = tpl.content.cloneNode(false); shadow.append(n);
  2. shadow.innerHTML = tpl.outerHTML;
  3. const n = document.getElementById(‘tpl’).content.cloneNode(true); shadow.appendChild(n);
  4. shadow.appendChild(document.getElementById(‘tpl’));
正解
  1. const n = document.getElementById(‘tpl’).content.cloneNode(true); shadow.appendChild(n);
解説

<template> の描画用コンテンツは template.content にあり、これを cloneNode(true) で深いコピーし、Shadow root に挿入する。テンプレート要素自体を移動してはならない。

使用例(サンプルコード)

[ html ]

<script>
  class MyBox extends HTMLElement {
    constructor(){
      super();
      const root = this.attachShadow({mode:'open'});
      const tpl = document.getElementById('tpl');
      root.appendChild(tpl.content.cloneNode(true));
    }
  }
  customElements.define('my-box', MyBox);
</script>