LoginSignup
2
3

More than 5 years have passed since last update.

templateタグはクローンしてから使おう

Last updated at Posted at 2018-04-03

MDN web docsのサンプル

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>

<table id="producttable">
  <thead>
    <tr>
      <td>UPC_Code</td>
      <td>Product_Name</td>
    </tr>
  </thead>
  <tbody>
    <!-- 必要に応じて既存のデータをここに含められます。 -->
  </tbody>
</table>

<template id="productrow">
  <tr>
    <td class="record"></td>
    <td></td>
  </tr>
</template>

<script>
// https://developer.mozilla.org/ja/docs/Web/HTML/Element/template

// templete 要素の content 属性の有無を確認することで、
// ブラウザが HTML template 要素をサポートしているかテストします。
if ('content' in document.createElement('template')) {

  // 既存の HTML tbody と template の行を使って table をインスタンス生成します。
  var t = document.querySelector('#productrow'),
  td = t.content.querySelectorAll("td");
  td[0].textContent = "1235646565";
  td[1].textContent = "Stuff";

  // 新しい行を複製してテーブルに挿入します。
  var tb = document.getElementsByTagName("tbody");
  var clone = document.importNode(t.content, true);
  tb[0].appendChild(clone);

  // 新しい行を生成します。
  td[0].textContent = "0384928528";
  td[1].textContent = "Acme Kidney Beans";

  // 新しい行を複製してテーブルに挿入します。
  var clone2 = document.importNode(t.content, true);
  tb[0].appendChild(clone2);

} else {
  // HTML template 要素がサポートされていないので 
  // テーブルに行を追加するほかの方法を探します。
}

</script>
</body>
</html>

templateタグ書き換えちゃってる!

上記サンプルのjsを解説するとこんな感じ。

templateタグをいじっちゃうので使い回すときとか危険だなと思いました。


  var t = document.querySelector('#productrow');
  var tb = document.getElementsByTagName("tbody");

  // <template>タグに値をセット
  td = t.content.querySelectorAll("td");
  td[0].textContent = "1235646565";
  td[1].textContent = "Stuff";
  // 複製してテーブルに挿入
  var clone = document.importNode(t.content, true);
  tb[0].appendChild(clone);

  // <template>タグに値をセット(※一つ前に追加したデータを上書き!危険!)
  td[0].textContent = "0384928528";
  td[1].textContent = "Acme Kidney Beans";
  // 複製してテーブルに挿入
  var clone2 = document.importNode(t.content, true);
  tb[0].appendChild(clone2);

推奨:templateタグは汚さない

まずtemplateタグをクローンしてから使いましょう。


  var t = document.querySelector('#productrow');
  var tb = document.getElementsByTagName("tbody");

  // <template>の中身を複製
  var clone = document.importNode(t.content, true);
  // 複製したタグに値をセットしてテーブルに挿入
  td = clone.querySelectorAll("td");
  td[0].textContent = "1235646565";
  td[1].textContent = "Stuff";
  tb[0].appendChild(clone);

  // <template>の中身を複製(※<template>は綺麗なまま)
  var clone = document.importNode(t.content, true);
  // 複製したタグに値をセットしてテーブルに挿入
  td = clone.querySelectorAll("td");
  td[0].textContent = "0384928528";
  td[1].textContent = "Acme Kidney Beans";
  tb[0].appendChild(clone);
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3