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. Sorry, never mind! :-) You already answered my question:
    “It’ not necessary to create DIV element (you can append only text node to the TD element)”

  2. Hi,

    Is it possible to add the whole table itself depending on user input? Example there is a table for house but people may have more than one house and if they have, once you click ADD, boom another table to write the details?

    Thank you in advance!

  3. Hi,

    Is it possible, when we click on add column button and on the place of the number we get the same value which is heading like when we click on add column we get no (0,1,2 etc) but I wnat know if i want the value like (small, html, table) on click on add column at the place of number how. plz tell me the js code.

  4. HI I am not an expert however a ok programmer on Javascript platform.

    I have created a programme that appends data into notepad using Java Scripting however I wish to store my data into excel sheet with a condition that: –

    1. Code opens the existing excel workbook and checks for the last used cell in column A.
    2. Appends / Write data on the next cell (i.e. blank cell) and creates a repository of my data records being punched.

    My dataset contains values HTML form Input fields that carry text values updated by users.

    I have created a function that goes as below however this overwrites values on each submit event. I am not sure who to create the needed interaction between JavaScript & Excel to loop and find the blank cell to append my data.

    I need your assistance to help code this for my project at my work place.

    my code is as below: –

        function WriteToFile(passForm) {
          var fso = new ActiveXObject("Scripting.FileSystemObject");
          var fileLoc = "H:\\sample.csv";
          var file = fso.CreateTextFile(fileLoc, true);
          file.writeline(passForm.FirstName.value + ',' + passForm.LastName.value);
          file.Close();
          alert("Data successfully submitted to DB");
         }
    

Leave a Comment