Create table using Javascript

Manny Fitzgerald picture Manny Fitzgerald · Feb 1, 2013 · Viewed 527.6k times · Source

I have a JavaScript function which creates a table with 3 rows 2 cells.

Could anybody tell me how I can create the table below using my function (I need to do this for my situation)?

Here is my javascript and html code given below:

Answer

Cerbrus picture Cerbrus · Feb 1, 2013

Slightly shorter code using insertRow and insertCell:

function tableCreate(){
    var body = document.body,
        tbl  = document.createElement('table');
    tbl.style.width  = '100px';
    tbl.style.border = '1px solid black';

    for(var i = 0; i < 3; i++){
        var tr = tbl.insertRow();
        for(var j = 0; j < 2; j++){
            if(i == 2 && j == 1){
                break;
            } else {
                var td = tr.insertCell();
                td.appendChild(document.createTextNode('Cell'));
                td.style.border = '1px solid black';
                if(i == 1 && j == 1){
                    td.setAttribute('rowSpan', '2');
                }
            }
        }
    }
    body.appendChild(tbl);
}
tableCreate();

Also, this doesn't use some "bad practices", such as setting a border attribute instead of using CSS, and it accesses the body through document.body instead of document.getElementsByTagName('body')[0];