1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

templateタグはcontent.firstElementChild.cloneNode(true)がおすすめ

Last updated at Posted at 2021-10-29

はじめてtemplateタグを使って、すこし嵌りました。

MDNのtemplateタグの使い方のサンプルは、template.content.cloneNodeを行っています。
私は最初これはtr要素だと思っていました。trにidを設定するつもりで
clone.setAttribute('id','id_of_tr_element')を行ったのですが、設定できないなとおもっていたところ、これはDocumentFragmentでした。

以下はMDNからの抜粋

    // 既存の HTML tbody と template の行を使って
    // table をインスタンス生成します。
    var tbody = document.querySelector("tbody");
    var template = document.querySelector('#productrow');

    // 新しい行を複製して表に挿入します。
    var clone = template.content.cloneNode(true);
    // cloneがtrだと思っていた
    var td = clone.querySelectorAll("td");
    td[0].textContent = "1235646565";
    td[1].textContent = "Stuff";

    tbody.appendChild(clone);
<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>

これはMDNのページでもDocumentFragment の落とし穴の回避 として記載がありました。

templateタグの子として複数要素ある場合でなければ、template.content.firstElementChild.cloneNode(true)が楽ちんです。

難しいことをしているわけではないだろうとおもってドキュメントを最後まで読むのを怠たりました。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?