Creating tables dynamically in client-side

You might find issues displaying dynamically created tables in Internet Explorer using JavaScript. I felt the necessity of posting this after I realized the reason why my tables were displaying properly in Firefox and other browsers but not in IE.

There is 2 reasons for that to happen: First, every table structure are supposed to be written with a tbody tag. Even if you don’t write it on your HTML document, browsers will add it automatically. Firefox adds a tbody automatically when you dynamically create a table, but IE doesn’t.

This is the code you can use to create a table. It also shows how to set the style of the elements on the fly:

<script type="text/javascript">

    var tbody = document.createElement('tbody'); //you must create a tbody

    for(i = 0; i < 10; i++){

        var tr = document.createElement('tr');

        var tdName = document.createElement('td');
        tdName.setAttribute("style", "width:275px;text-align:center"); //setting the style



    var table = document.createElement('table');


    //When appending this table using jQuery, you need a work-around. Take a look at the code below:

    if (typeof(table) != 'undefined') {
        if ($.browser.msie) // if Internet Explorer, append the table differently
            $("#div").append("<table border=0 width='100%'>" + table.innerHTML + "</table>");

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s