template要素
template要素はJavaScriptなどで利用するテンプレートを記述する為の要素です。
template要素は2014年2月4日にHTML5に追加された新しい要素です。
次のようにtemplate要素内にテンプレートとして利用したい内容を記述します。
<table>
<thead>
<tr>
<th>Name</th>
<th>Color</th>
<th>Sex</th>
<th>Legs</th>
</tr>
</thead>
<tbody>
<template id="row">
<tr><td></td><td></td><td></td><td></td></td>
</template>
</tbody>
</table>
テンプレートを利用するには以下のようにJavaScriptを利用しテンプレート内にデータを挿入します。
var data = [{
name : "太郎",
color : "青",
sex : "男",
legs : 26.5
},{
name : "花子",
color : "赤",
sex : "女",
legs : 23.5
}];
var template = document.querySelector('#row');
for (var i = 0; i < data.length; i += 1) {
var cat = data[i];
var clone = template.content.cloneNode(true);
var cells = clone.querySelectorAll('td');
cells[0].textContent = cat.name;
cells[1].textContent = cat.color;
cells[2].textContent = cat.sex;
cells[3].textContent = cat.legs;
template.parentNode.appendChild(clone);
}
template要素に対応していないブラウザではtemplate要素の内容が出力されますので以下のようにCSSで非表示にすると良いでしょう。
template{
display:none;
}
参考URL
4.12.3 The template element - HTML5 - W3C
登録日 : 2014年05月02日 最終更新日 : 2014年5月2日