Creating Tables

All of the prior examples of using the DOM with tables have been updating tables already in the web page. What about when you need to generate the table entirely with JavaScript?

To do this we need to use just two DOM createElement calls - one to create the table tag itself and one to create the tbody tag within the table. All of the other table tags - the thead tag and the rows and cells can all be created using the table specific DOM methods. Don't ask me why there isn't a create method for the tbody tag since there is one for all the other parts of a table but that's just the way JavaScript is.

Since the calls you need to create the actual table are the same regardless of what content you are going to put in the table, we'll keep the content of this example very simple and just create a multiplication table similar to that which children might use. We'll insert that text content using innerHTML both to demonstrate the one spot in the table where it can be used and also because that keeps the code a bit shorter than if we were to use DOM calls to insert the content. We'll also style the table with CSS even though the table will not be there for people with JavaScript disabled as the CSS we specify will only be applied if the table is created. We can add a class to those cells we wish to style differently where there is no other way of identifying them as that is both neater than adding the styles directly to each tag and nowhere near as complex as trying to add a colgroup and col tags to the table (which would have required additional createElement calls).

HTML
CSS
JavaScript

This site is © copyright Stephen Chapman - Felgall Pty Ltd 2011-2014.

Privacy Policy | Terms and Conditions

You are welcome to use any the example JavaScript from this site in the scripts for your site or any that you develop for others but may not use the longer example scripts that contain a copyright notice in any other way without permission.