LoginSignup
3
4

More than 5 years have passed since last update.

実践DOM操作 by jQuery

Last updated at Posted at 2017-05-26

概要

空のHTMLにDOM要素を捜査して動的にhtmlを追加します。

完成品 → https://codepen.io/ksyunnnn/pen/bWJVaY

実践

データを元に生成する感じにします。

index.html
<div class="container" id="tabMonth">
  <button>Create</button>
  <ul></ul>
</div>
index.js
function tabMonth(data,id) {
  $ul = $('#tabMonth > ul');
  for (let k in data) {
    // DOM生成(プロパティも設定)
    $a = $("<a></a>", {
      href: "example.com/tab/"+data[k].id,
      "class": "nav-link"
    });
    // aタグに入れるテキスト追加
    $a.text(data[k].year+""+data[k].month+"")

    // listに設定したいクラスを指定しておく
    var add = 'nav-item'+(data[k].id===id?' active':'');
    // DOM生成(プロパティも設定※aタグとは違う方法で)
    $list = $('<li>').addClass(add);

    // 追加
    $list.append($a)
    $ul.append($list);
  }
}

// 元データ
var data = [{
  "id": "1212",
  "year": "2017",
  "month": "1"
}, {
  "id": "1313",
  "year": "2017",
  "month": "2"
},{
  "id": "1212",
  "year": "2017",
  "month": "3"
}, {
  "id": "1313",
  "year": "2017",
  "month": "4"
}, {
  "id": "1414",
  "year": "2017",
  "month": "5"
},{
  "id": "1212",
  "year": "2017",
  "month": "6"
}];

// 処理部分
$("button").click(function(e) {
    tabMonth(data,"1414");
  });

できたできた

参考: http://qiita.com/nekoneko-wanwan/items/227ccad5f8cc449e91e9

3
4
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
3
4