11
14

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 5 years have passed since last update.

javascriptでtableをループ その2-2

Last updated at Posted at 2014-11-11

HTML直書きしないことを想定してtrごと回してみたバージョン

html
<table>
  <thead>
    <tr>
      <td>項目1</td>
      <td>項目2</td>
      <td>項目3</td>
    </tr>
  </thead>
  <tbody id="tbodyID">
    <!-- ここをループ -->
  </tbody>
</table>
javascript
 <script>
      /*ページ(DOM)読み込み後に実行*/
      window.onload = function(){

          //tbodyのIDを取得(この中で処理します)
          var tbody = document.getElementById('tbodyID');

          for (i = 0; i < 5; i++){
              //tr エレメントを新規作成(ただ生成するだけ)
              var tr = document.createElement('tr');
              //列(td)用のループ
              for (j = 0; j < 5; j++){
                  //tdエレメントをを生成
                  var td = document.createElement('td');
                  //tdの中に入れたいモノをセット
                  td.innerHTML = 'こんにちは' + j;
                  //生成したtdをtrにセット
                  tbody.appendChild(td);
              }//列用のループ閉じ
              //tr エレメントをtbody内に追加(ここではじめて表示される)
              tbody.appendChild(tr);
          }//行用のループ閉じ

      };
  </script>
11
14
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
11
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?