Shadow DOM

トップ > アラカルト > Shadow DOM

概要

Shadow DOM は、Webコンポーネント(Web Components) と呼ばれる技術群のひとつです。見栄え(スタイル)がカプセル化されたテンプレートを用いて、データを表示していくことが可能です。Chrome 35 や Opera 22 でサポートされています。

サンプル

HTML
<template id="shadow-dom-template">
  Title: [ <slot name="title"></slot> ],
  Artist: [ <slot name="artist"></slot> ]
</template>

<div class="song">
  <span slot="title">Let it be</span>
  <span slot="artist">The Beatles</span>
</div>

<div class="song">
  <span slot="title">Hotel California</span>
  <span slot="artist">The Eagles</span>
</div>

<script>
var hostElements = document.getElementsByClassName("song");
for (var i = 0; i < hostElements.length; i++) {
  var rootElement = hostElements[i].attachShadow({mode: "open"});
  var templeteContent = document.getElementById("shadow-dom-template").content.cloneNode(true);
  rootElement.appendChild(templeteContent);
}
</script>
表示
Let it be The Beatles
Hotel California The Eagles

関連

<template>, <slot>, slot, Webコンポーネント, カスタム要素, Shadow DOM, HTMLテンプレート

リンク


Copyright (C) 2017 杜甫々
初版:2017年11月19日 最終更新:2017年11月19日
http://www.tohoho-web.com/ex/shadow-dom.html