HTML <template>タグ
例
<template> タグを使用すると、ページ読み込み時にはタグ内のコンテンツは表示されず、読み込み後に JavaScript を使用して表示できます:
<button onclick="showContent()">隠れたコンテンツを表示</button>
<template>
<h2>logo</h2>
<img src="/static.jyshare.com/images/example-logo.png" >
</template>
<script>
function showContent() {
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
}
</script>
試してみる »
ブラウザサポート
表内の数字は、その要素をサポートする最初のブラウザのバージョン番号を示します。
| 要素 | |||||
|---|---|---|---|---|---|
| <template> | 26.0 | 13.0 | 22.0 | 8.0 | 15.0 |
タグの定義と使い方
<template> タグは、ページ読み込み時に非表示にされるコンテンツを定義します。このタグ内のコンテンツは、後で JavaScript を使用してレンダリングできます。
繰り返し使用する必要がある HTML コードがある場合は、次のように使用できます<template>共通のテンプレートとして設定します。
その他の例
例
例では、配列の各要素を新しい div 要素で Web ページに埋め込んでいます。各 div 要素の HTML コードは template 要素内にあります:
<template>
<div class="myClass">私が好きなもの:</div>
</template>
<script>
var myArr = ["Google", "サンプル", "Taobao", "Wiki", "Zhihu", "Baidu"];
function showContent() {
var temp, item, a, i;
temp = document.getElementsByTagName("template")[0];
item = temp.content.querySelector("div");
for (i = 0; i < myArr.length; i++) {
a = document.importNode(item, true);
a.textContent += myArr[i];
document.body.appendChild(a);
}
}
</script>
試してみる »
例
ブラウザが template タグをサポートしているか確認する:
if (document.createElement("template").content) {
document.write("お使いのブラウザは template タグをサポートしています!");
} else {
document.write("お使いのブラウザは template タグをサポートしていません!");
}
試してみる »
グローバル属性
<time> タグのサポートHTML のグローバル属性。
その他の拡張