HOWTO · JavaScript

JavaScript を使用してテーブルを作成する

この記事では、JavaScript を使用してテーブルを作成する方法を説明します。

このページの内容

document.createElement() で要素を組み立て、textContent でセルのテキストを設定し、完成した表を appendChild() でページ上のコンテナーに追加すると、JavaScript のデータから HTML テーブルを作成できます。ページの実行中に変化するデータから行を作る場合に便利です。

HTMLテーブルの構造と必要な要素

テーブルでは、入れ子になった要素で内容を表します。table 要素の中に行(tr)があり、各行には見出しセル(th)またはデータセル(td)が入ります。行や列の項目名を示すセルには th を使い、通常のデータには td を使います。見出しセルは thead 内に限らず、テーブル本体の行見出しにも使用できます。

thead と tbody は、それぞれ見出し行と本体の行をまとめる要素です。大きなテーブルの整理に役立ちますが、すべてのテーブルに必要なわけではありません。必要に応じて tfoot に集計行やフッター行をまとめることもできます。小さなテーブルなら、基本となるのは table とその行・セルです。構造が分かりやすくなる場合に、グループ化要素を追加してください。

JavaScriptでテーブルを作成してデータを入れる

以下の例では、見出し行を1行、データ行を2行作成します。列は番号、名前、会社の3つで、各セルには textContent を使って通常のテキストを設定します。これにより、値はHTMLとして解析されずテキストとして扱われるため、ユーザー入力を含む可能性があるデータには、より安全な初期設定となります。

以下のブラウザー向け例では、標準のDOM APIを使い、完成したテーブルを既存の #table-container に追加します。続くNode.jsの例は、小さなDOM風モデルを使って行を組み立てる処理とその件数を示すもので、ブラウザーに表示されるテーブルを作るものではありません。

ブラウザーで開くページの例(HTMLファイルとして保存し、ブラウザーで開いてください):

このセクションのコードと表示されるラベルや出力は英語のままです。

<!doctype html>
<html lang="en">
  <body>
    <div id="table-container"></div>
    <script>
      const container = document.getElementById("table-container");
      const table = document.createElement("table");
      const thead = document.createElement("thead");
      const tbody = document.createElement("tbody");
      const headings = ["No.", "Name", "Company"];
      const records = [
        ["1", "James Clerk", "Netflix"],
        ["2", "Adam White", "Microsoft"]
      ];

      const headerRow = document.createElement("tr");
      for (const heading of headings) {
        const cell = document.createElement("th");
        cell.textContent = heading;
        headerRow.appendChild(cell);
      }
      thead.appendChild(headerRow);

      for (const record of records) {
        const row = document.createElement("tr");
        for (const value of record) {
          const cell = document.createElement("td");
          cell.textContent = value;
          row.appendChild(cell);
        }
        tbody.appendChild(row);
      }

      table.appendChild(thead);
      table.appendChild(tbody);
      container.appendChild(table);
    </script>
  </body>
</html>

次の自己完結型JavaScript例を実行します。

class Element {
  constructor(name) {
    this.name = name;
    this.children = [];
    this.textContent = "";
  }

  appendChild(child) {
    this.children.push(child);
    return child;
  }
}

const document = {
  createElement(name) {
    return new Element(name);
  },
  body: new Element("body")
};

const container = document.createElement("div");
container.id = "table-container";
document.body.appendChild(container);

const table = document.createElement("table");
const thead = document.createElement("thead");
const tbody = document.createElement("tbody");
const headings = ["No.", "Name", "Company"];
const records = [
  ["1", "James Clerk", "Netflix"],
  ["2", "Adam White", "Microsoft"]
];

const headerRow = document.createElement("tr");
for (const heading of headings) {
  const cell = document.createElement("th");
  cell.textContent = heading;
  headerRow.appendChild(cell);
}
thead.appendChild(headerRow);

for (const record of records) {
  const row = document.createElement("tr");
  for (const value of record) {
    const cell = document.createElement("td");
    cell.textContent = value;
    row.appendChild(cell);
  }
  tbody.appendChild(row);
}

table.appendChild(thead);
table.appendChild(tbody);
container.appendChild(table);

const tableElement = container.children[0];
const headerCells = tableElement.children[0].children[0].children;
const bodyRows = tableElement.children[1].children;
console.log(`${headerCells.length} headings, ${bodyRows.length} data rows`);
3 headings, 2 data rows

document.createElement() は、文字列で指定された要素名を受け取り、新しい要素を返します。このコードでは各行に tr を作成し、その中に th または td のセルを追加します。各セルに値を設定してから、行を thead または tbody に入れます。最後に、それらのグループをテーブルに入れ、テーブルを例の冒頭で作成したコンテナーに追加します。

自分で管理するページなら、コンテナーは <div id="table-container"></div> のように用意できます。ブラウザー上のコードでは、document.getElementById("table-container") で既存の要素を選び、完成したテーブルをそこに追加します。対象要素が存在するように、ページ内でコンテナーの後にスクリプトを配置するか、ドキュメントの読み込み後に実行してください。見た目はJavaScriptとは分けてCSSで整えます。たとえば table、th、td に枠線や余白を設定できます。JavaScriptは構造と内容を作り、CSSは表示方法を制御します。

DOMにテーブルを追加して確認する

完成したテーブルは、container.appendChild(table) で選択したコンテナーに追加します。これにより、ページのほかの部分をそのままにして、テーブルがコンテナー内に入ります。既存の内容を置き換えたい場合は、追加する前にその内容を意図的に消してください。消さないまま実行するたびに、テーブルがもう1つ追加されます。

結果を確認するには、ブラウザーの開発者ツールを開き、Elementsパネルでコンテナーを調べます。中には table があり、thead に th セル3つを含む行が1行、tbody に td セル3つを含む行が2行あるはずです。表示される表の見出しは「No.」「Name」「Company」で、その下にJames Clerk / NetflixとAdam White / Microsoftが並びます。これらはコード例にそのまま残した英語のラベルと値です。表が見つからない場合は、コンテナーのIDとスクリプトの実行タイミングを確認してください。通常のテキスト値には、データを innerHTML に代入するのではなく、引き続き textContent を使用します。