LoginSignup
2
2

More than 5 years have passed since last update.

配列のデータからDOMを作る

Last updated at Posted at 2018-07-30

表題のとおり。
jQueryを使わずにDOMを作ります。

HTML

tbodyのなかにDOMを作ります

<table>
 <tbody></tbody>
</table>

Data

const FAMILY = [
  {
    "id": 1,
    "name": "悟空"
  },
  {
    "id": 2,
    "name": "悟飯"
  },
  {
    "id": 3,
    "name": "悟天"
  },
  {
    "id": 4,
    "name": "チチ"
  }
]

Javascript

パターン1

FAMILY.map(t => {
  const list = `
    <td>${t.id}</td>
    <td>${t.name}</td>
  `
  const trElement = document.createElement('tr');
  trElement.innerHTML = list;
  document.querySelector('tbody').appendChild(trElement);
});

パターン2

document.querySelector('tbody').innerHTML = FAMILY.map(t => (
  `
    <tr>
      <td>${t.id}</td>
      <td>${t.name}</td>
    </tr>
  `
)).join('');
2
2
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
2