Click here to Skip to main content
15,891,431 members
Articles / Web Development / HTML

Creating HTML Tables with JavaScript/DOM Methods

Rate me:
Please Sign up or sign in to vote.
3.63/5 (8 votes)
6 Oct 2015CPOL 24.4K   6   4
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.

This article was originally posted at http://web-engineering.info/node/38

License

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


Written By
Instructor / Trainer
Germany Germany
Researcher, developer, instructor and cat lover.

Co-Founder of web-engineering.info and the educational simulation website sim4edu.com.

Comments and Discussions

 
GeneralMessage Closed Pin
8-Oct-15 22:59
Avani As8-Oct-15 22:59 
SuggestionSuggestion Pin
Marco Bertschi6-Oct-15 22:06
protectorMarco Bertschi6-Oct-15 22:06 
GeneralRe: Suggestion Pin
Pete O'Hanlon6-Oct-15 22:14
mvePete O'Hanlon6-Oct-15 22:14 
GeneralRe: Suggestion Pin
Marco Bertschi6-Oct-15 22:59
protectorMarco Bertschi6-Oct-15 22:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.