Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Creating HTML Tables with JavaScript/DOM Methods

3.63/5 (8 votes)
6 Oct 2015CPOL 25K  
The proper way of creating an HTML table with JavaScript and inserting it into the HTML body element is using the DOM methods insertRow and insertCell.

The proper way of creating an HTML table with JavaScript and inserting it into the HTML body element is using the DOM methods insertRow and insertCell, as in the following code example:

JavaScript
function createTable() {
  var i=0, rowEl=null,
      tableEl = document.createElement("table");
  // create 10 table rows, each with two cells
  for (i=1; i <= 10; i++) {
    rowEl = tableEl.insertRow();  // DOM method for creating table rows
    rowEl.insertCell().textContent = "table cell "+ i +"-1" ;      
    rowEl.insertCell().textContent = "table cell "+ i +"-2" ;      
  }
  document.body.appendChild( tableEl);
}

The DOM method insertRow can be called on a table element for creating and inserting a new row, while insertCell can be called on a row element for creating and inserting a new cell.

Many web developers are not familiar with the DOM, or still think (mistakenly) that it's not well supported by browsers or too slow, and create HTML elements in the form of strings that are inserted into the DOM using the innerHTML attribute. This is not a safe, and certainly not a best practice, approach.

The following UML class diagram summarizes the DOM interfaces for programmatically manipulating table elements. Notice that insertRow can also be called on tHead and tFoot, which are table section elements.

Image 1

For reading more about how to use DOM attributes and methods for building web apps, see my book Building Front-End Web Apps with Plain JavaScript.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)