LoginSignup
30
19

More than 5 years have passed since last update.

templateタグを使う

Posted at

MDNを参考に、templateタグをつかって簡単なTODOリストをつくってみる。

htmlファイルを用意する

最低限必要なのは入力フォームとTODOが追加されていくリスト、そして今回の肝であるtemplate。
とりあえず↓のようにした。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>template</title>
</head>
<body>

<div>
    <input type="text" id="title" />
    <button id="add">Add</button>
</div>

<ul id="todo">
    <template id="template">
        <li>
            <span>titleが入る</span>
            <button>Delete</button>
        </li>
    </template>
</ul>

</body>
</html>

jsでtemplateを扱う

ここでやることは大きく次の4つ。
1. template要素を取得し
2. 複製し
3. なにかして
4. DOMに追加する

script.js
// template要素を取得し
var template = document.getElementById('template');
// 複製し
var clone = document.importNode(template.content, true);
// なにかして
clone.firstElementChild.style.background = '#'+Math.floor(Math.random()*16777215).toString(16);
// DOMに追加する
document.getElementById('todo').appendChild(clone);

templateの扱い方はこれだけ。あとはこれを使ってTODOリストっぽく肉付けしていく。

肉付け

した。

script.js
(function () {

    // template
    var template = document.getElementById('template');

    // titleを入力するinput要素
    var title = document.getElementById('title');

    // todoリスト
    var todo = document.getElementById('todo');

    // Addボタン
    document.getElementById('add').addEventListener('click', function () {
        // 入力されていなければ何もしない
        if (!title.value) return;

        // templateから要素を複製する
        var clone = document.importNode(template.content, true);

        /* 複製した要素になにかする */
        // 背景色を変更
        clone.firstElementChild.style.background = '#'+Math.floor(Math.random()*16777215).toString(16);
        // 入力されたtitleをいれる
        clone.querySelector('span').textContent = title.value;
        // ボタンが押されたらリストから削除する
        clone.querySelector('button').addEventListener('click', function () {
            var parent = this.parentNode;
            parent.parentNode.removeChild(parent);
        });

        // 複製した要素をリストに追加する
        todo.insertBefore(clone, todo.firstChild);

        // titleの値を空にしておく
        title.value = '';
    });

})();

まぁ動きわかればおkだべ。

demo

Tips

templateタグが対応していないゴミのようなブラウザでは、templateタグで囲っている部分がふつうに表示されてしまう。
なのでcssでtemplate振ったidなどに対してdisplay: noneとか当てておくと安心。

というね。

30
19
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
30
19