template要素
template要素は、スクリプトによりクローン化で複製し挿入するHTML要素の断片を示す要素。
| カテゴリー | メタデータ・コンテンツ、フロー・コンテンツ、フレージング・コンテンツ、スクリプト・サポート要素。 |
|---|---|
| コンテキスト |
メタデータ・コンテンツを内包できる要素内で使用できる。 フレージング・コンテンツを内包できる要素内で使用できる。 スクリプト・サポート要素(script要素、template要素)を内包できる要素内で使用できる。 span属性がないcolgroup要素の子要素として使用できる。 |
| コンテンツ・モデル | 下記の何れか。 |
| 属性 | グローバル属性。 |
| ブラウザ対応 | ![]() ![]() ![]() |
構文
<template>HTML要素</template>
要点
サンプルコード
リスト
<ol> <template> <li></li> </template> </ol>
表(テーブル)
<table> <template> <tr> <td></td> <td></td> <td></td> </tr> </template> </table>
サンプル
リスト
HTMLソースコード
<ol>
<template id="sampleLi">
<li></li>
</template>
</ol>
<script>
var $sampleData = ['項目1','項目2','項目3'];
var $sampleTemplate = document.querySelector('#sampleLi');
for (var $i = 0; $i < $sampleData.length; $i += 1) {
var $sampleClone = $sampleTemplate.content.cloneNode(true);
$sampleClone.querySelector('li').textContent = $sampleData[$i];
$sampleTemplate.parentNode.appendChild($sampleClone);
}
</script>
実際の表示
表(テーブル)
HTMLソースコード
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>template要素のサンプル・ドキュメント</title>
<style>
table {
font-size: 24px;
}
table td {
padding: 0.3em 1em;
}
</style>
</head>
<body>
<h1>template要素のサンプル</h1>
<script>
var $data = [
{ name: '太郎', sansuu: 100, kokugo: 70, eigo: 53 },
{ name: '花子', sansuu: 51, kokugo: 100, eigo: 95 },
{ name: '次郎', sansuu: 82, kokugo: 61, eigo: 100 },
];
</script>
<table border="1">
<thead>
<tr>
<th>名前</th>
<th>算数</th>
<th>国語</th>
<th>英語</th>
</tr>
</thead>
<tbody>
<template id="row">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</template>
</tfoot>
</table>
<script>
var $template = document.querySelector('#row');
for (var i = 0; i < $data.length; i += 1) {
var $row = $data[i];
var $clone = $template.content.cloneNode(true);
var $cells = $clone.querySelectorAll('td');
$cells[0].textContent = $row.name;
$cells[1].textContent = $row.sansuu;
$cells[2].textContent = $row.kokugo;
$cells[3].textContent = $row.eigo;
$template.parentNode.appendChild($clone);
}
</script>
</body>
</html>


