65.9K
CodeProject is changing. Read more.
Home

Creating HTML Tables with JavaScript/DOM Methods

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.63/5 (8 votes)

Oct 7, 2015

CPOL
viewsIcon

25012

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:

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.

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.