Adding table rows and columns in JavaScript

With insertRow() method you can insert a new row at the specified position in HTML table. After row is created, use insertCell() method to insert a table cell. Wrap this methods in JavaScript functions and you have code to dynamically add new rows and columns in the HTML table. Please try to click the buttons below …






Small
HTML
table

When you click the “Add row” button, appendRow() function is called. Function is simple, table row is inserted at the last position, and loop iterates through table cells in the first row. Why first row? Because you have to know the number of columns. For each step (cell in the first row), createCell() function creates and attaches DIV element to the newly created table cell.

// append row to the HTML table
function appendRow() {
    var tbl = document.getElementById('my-table'), // table reference
        row = tbl.insertRow(tbl.rows.length),      // append table row
        i;
    // insert table cells to the new row
    for (i = 0; i < tbl.rows[0].cells.length; i++) {
        createCell(row.insertCell(i), i, 'row');
    }
}

// create DIV element and append to the table cell
function createCell(cell, text, style) {
    var div = document.createElement('div'), // create DIV element
        txt = document.createTextNode(text); // create text node
    div.appendChild(txt);                    // append text node to the DIV
    div.setAttribute('class', style);        // set DIV class attribute
    div.setAttribute('className', style);    // set DIV class attribute for IE (?!)
    cell.appendChild(div);                   // append DIV to the table cell
}

createCell() also sets class attribute (needed for the red and green background color) to the DIV element. It’ not necessary to create DIV element (you can append only text node to the TD element), but this is a good example of how to create and append new element to the table cell. appendColumn() is similar to the appendRow() function. For each table row, new cell is inserted to the last position in the row.

// append column to the HTML table
function appendColumn() {
    var tbl = document.getElementById('my-table'), // table reference
        i;
    // open loop for each row and append cell
    for (i = 0; i < tbl.rows.length; i++) {
        createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
    }
}

Here is code used to delete table rows and columns (“Delete both” button, calls both functions).

// delete table rows with index greater then 0
function deleteRows() {
    var tbl = document.getElementById('my-table'), // table reference
        lastRow = tbl.rows.length - 1,             // set the last row index
        i;
    // delete rows with index greater then 0
    for (i = lastRow; i > 0; i--) {
        tbl.deleteRow(i);
    }
}

// delete table columns with index greater then 0
function deleteColumns() {
    var tbl = document.getElementById('my-table'), // table reference
        lastCol = tbl.rows[0].cells.length - 1,    // set the last column index
        i, j;
    // delete cells with index greater then 0 (for each row)
    for (i = 0; i < tbl.rows.length; i++) {
        for (j = lastCol; j > 0; j--) {
            tbl.rows[i].deleteCell(j);
        }
    }
}

85 thoughts on “Adding table rows and columns in JavaScript”

  1. Hi Dbunic,

    Having an issue in the above said approach of setting name/id property for the newly created form element:

    // define reference to the child element
     el = newcell.childNodes[0]; 
    // set new Name to the form element 
    el.name = 'someName'; 
    // set Id to the referenced element 
    el.id = 'someId'; 
    

    Issue

    For eg. I have two rows in the form and values are already populated for the two rows and I’m adding a new row using AddRow function:

    function addRow(tableID) {
        var table = document.getElementById('dataTable');
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;
        // alert("The Row count is "+rowCount);
        // alert("The colCount count is "+colCount);
        var k = (rowCount - 1) * (colCount - 1);
        for (var i = 0; i < colCount + 1; i++){
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[1].cells[i].innerHTML;
            switch(newcell.childNodes[0].type) {
            case "text":
                var e1 = newcell.childNodes[0];
                e1.name = "detailListId[" + (++k) + "].restText";
                newcell.childNodes[0].value = "";
                break;
            case "checkbox":
                newcell.childNodes[0].checked = false;
                break;
            case "select-one":
                newcell.childNodes[0].selectedIndex = 0;
                break;
            }
        }
    }
    

    The newly created row is taking the reference of the all cells of the second row (index == 1) as below

    Row1 (already populated)

    <A></A>

    Newly Added row (name is very similar to first row)

    <A></A>

    Can you please help.

    Thanks,
    Ramesh

  2. Hey dbunic,
    Your tips are really good. But, I have a doubt that i think it´s a little more complicated. I want to clone the table. And the table I wanna clone is inside another table, something like:

    *****
    **********
    **********
    *******Click the button to clone the table and then********
    **********
    **********
    *****
    
  3. @Ramesh – It seems some HTML code is missing (I suppose that WordPress filtered your comment). Anyway, I prepared and sent offline example to you so we can continue discussion.

    @Priscilla – every node in a DOM can be cloned. Please see the documentation for cloneNode method. Here is how DIV element is cloned in REDIPS.drag lib:

    var div_cloned = div.cloneNode(true);
    

    Cloned node will not be a part of the document until it is added to another node that is part of the document using appendChild or a similar method. If input parameter is set to true then children of the node will be also cloned.

  4. OK , I have a quick question regarding Tables.
    I am fairly new to JavaScript. taking evening classes. Now we have an excercise where we need to do the following:

    – user will get prompted their age
    – then it prompts them for the Gender
    – now, depending on what they enter, I need to create a table that:
    has rows and columns equal to the age entered and then the cells need to be filled with the male/female gender sign.

    To be frank I have no idea how I am going to approach this.
    I got the prompts and all working, but I am not able to apply that to the function.

  5. @Zark – You can reuse appendRow() function from this post. With two loops and age as input parameter JS code will look like:

    function appendRow(age) {
        var tbl = document.getElementById('mytable'), // table reference
            row,  // row reference
            i, j; // loop variables
        // open loop to insert table row
        for (i = 0; i < age; i++) {
            // append table row
            row = tbl.insertRow(tbl.rows.length);
            // insert table cells to the new row
            for (j = 0; j < age; j++) {
                row.insertCell(j);
            }
        }
    }
    

    This code is a good enough to start with. Here is also simple HTML to use with JS code:

    <html>
    <head>
        <script type="text/javascript" src="script.js"></script>
        <style>
            td {width: 10px; height: 10px}
        </style>
    </head>
    <body onload="appendRow(10)">
        <table border="1" id="mytable"></table>
    </body>
    </html>
    
  6. It works like a charm, with the age variable.
    Now just one more question.

    When I have the gender variable. How would I tell it to pupulate the cells with whatever I need to put in them?

  7. @Zark – Here is modified function:

    // input parameter is age and gender
    function appendRow(age, gender) {
        var tbl = document.getElementById('mytable'), // table reference
            row,  // row reference
            cell, // cell reference
            i, j; // loop variables
        // open loop to insert table row
        for (i = 0; i < age; i++) {
            // append table row
            row = tbl.insertRow(tbl.rows.length);
            // insert table cells to the new row and set cell content
            for (j = 0; j < age; j++) {
                cell = row.insertCell(j);
                cell.innerHTML = gender;
            }
        }
    }
    

    Just send age and gender variables to the function and all table cells will be populated with gender value.

  8. Hi… this sees to really nice article… but a small problem …if u press it delete either rows or columns it deletes the complete rows & columns completely …. but if I need to delete a specific row of how to do it..

    regards
    Pravin Nair

  9. Great drag and drop tools. I’ve been trying out all of your examples and they are impressive. I do have a question that I’m hoping you can help me out with. It seems that when I try to add more than 11 columns, the drag and drop becomes erratic in those farther columns. It seems that i can only go so far to the outer columns, drop it, and then try to move column by column until i get to the outermost column. Again don’t get me wrong, the tool is incredible, but wondering if you have a quick fix that will allow me to play with 15, 20 or 25 columns? Going down rows works flawlessly. If this problem can’t be fixed it’s stil one of the best tools I’ve come across.

    Thanks in advance

  10. @Pravin Nair – This post displays how to begin adding table rows and columns in JavaScript. Here are shown only basic functionality. I have also prepared small REDIPS.table library which contains merge/split cells and add/delete rows/columns methods. Please see REDIPS.table documentation with all contained features.

    @Ron – REDIPS.drag should work nicely with really wide and long tables. Maybe the problem is due to DIV#drag dimensions. Please add the following style to the style.css file:

    #drag {
        border: 1px solid lime;
    }
    

    This will make DIV#drag visible. So, if DIV#drag is smaller than table, some columns may not work properly or will not be reachable at all. Just set correct width to the drag region and dragging should work fine. This problem is mentioned Appendix A documentation.

  11. I’m way new to JavaScripts and figuring things out on my own – by reading a lot of online forums and such. I’m working with an online spreadsheet that automatically adds a row (with info) when a linked form is submitted. I have another sheet for which I’ve customized a script to pull certain columns from the source sheet. For some reason, the target sheet doesn’t has to have an equal number of rows as the source sheet for the script to work.
    I’m trying to make the script compare the number of rows in each sheet and append any new rows if the target sheet is lacking, then run the script to pull the desired columns. I tried an if-else statement for the compare, but I get an error “cannot find method for appendRow()” – I don’t quite know how to fix that error. Can you help? The code is below:

    function importFunction(a) {
      var ss = SpreadsheetApp.openById("0ApTaY3v27-UqdElwZTBvanNpaC1UckpxaTJRZS1XNWc");
      var sourceSheet = ss.getSheets()[0];
      var ss2 = SpreadsheetApp.openById("0ApTaY3v27-UqdElwZTBvanNpaC1UckpxaTJRZS1XNWc");
      var targetSheet = ss2.getSheets()[1];
      var targetMax = targetSheet.getMaxRows();
      var values1 = sourceSheet.setActiveSelection("C:C").getValues();
      var values2 = sourceSheet.setActiveSelection("AD:AD").getValues();
      var values3 = sourceSheet.setActiveSelection("D:E").getValues();
      var values4 = sourceSheet.setActiveSelection("AE:AE").getValues();
      var values5 = sourceSheet.setActiveSelection("F:H").getValues();
      var values6 = sourceSheet.setActiveSelection("N:U").getValues();
      if(targetMax < values1.length)
        targetSheet.appendRow();
      else
        targetSheet.setActiveSelection("A:A").setValues(values1);
        targetSheet.setActiveSelection("B:B").setValues(values2);
        targetSheet.setActiveSelection("C:D").setValues(values3);
        targetSheet.setActiveSelection("E:E").setValues(values4);
        targetSheet.setActiveSelection("F:H").setValues(values5);
        targetSheet.setActiveSelection("I:P").setValues(values6);
    }
    
  12. Clarification – the target sheet HAS to have an equal number of rows for the script to work.

  13. My guess is that open spreadsheets use HTML table as a base, so if you are familiar with tables then modification of such script should not be a problem. Anyway, I’m glad you found the answer. Cheers!

  14. Hola si muy bueno este post me ayudo bastante, pero que pena tengo una pequeña inquietud me gustaria saber como puedo agregar en cada celda campos de texto, es decir a medida que se creen columnas con filas en las celdas se creen campos para luego ser insertados en una base de datos.

    Agradezco la ayuda.

  15. @Jenny – Hi, I don’t know Spanish so I used Google translator for your comment (sorry if your question was misunderstood). Anyway, if you want to append text fields in created rows / columns you can modify createCell() function like:

    function createCell(cell, text, style) {
        cell.innerHTML = '<input type="text" value="Hello"/>';
    }
    

    This function is called for every created table cell so you are free to customize it for your needs.

  16. Intention of this post is to show how is easy and simple manipulate HTML tables via JavaScript. Yes it’s possible to insert column instead of appending to table end. Please see my post Merge and split table cells with JavaScript where you will see complete functionality regarding adding/inserting table row/column. On the REDIPS.table documentation you will see how to define “index” for a new column (just search for column() method).
    ;)

Leave a Comment