Build HTML Table With Javascript

written in html, javascript

In this article i will show how handle a html table using the javascript and DOM manipulation. The gains of creat and handle the html tabel using js is that all of the tabel structure it´s easy to handle throught DOM. You can change all the table or you can change each cell or row independently.

To build a html table I built these scripts to show:

html table through js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   //Table class
  function Table(columns, rows){
      //Properties
      this.columns = columns;
      this.rows = rows;
      //create the html node <TABLE></TABLE>
      this.element = document.createElement(table);
  }
  //Prototype of Table Class
  Table.prototype = {
      //Method to build  a table
      build:function(){
          for(var l=0;l<this.rows;l++){
              //New row <TR></TR>
              var row = this.element.insertRow();
              for(var c=0;c<this.columns;c++){
                  //New cell<TD></TD>
                  var cell = row.insertCell();
                  cell.appendChild(document.createTextNode(Row :  + parseInt(l+1) +  Column:  + parseInt(c+1)))
              }
          }
      return this.element;
  }
  }
  function Main(){
      //Create a new table
      var newTable = new Table(5,5);
      //get the element 'content' and put the new table inside
      document.getElementById(content).appendChild(tabela.build());
  }

This is the simple and the easy way to build a html table using javascript.

Thanks.


Comments