Dream House

Courage to do something…

Removing table rows using JavaScript

Posted by Mohammad Sajjad Hossain on January 12th, 2008

In my last post I have shown how to duplicate a table row. Now if you let the user to duplicate a row then you will look for a solution to remove row dynamically using JavaScript. Use the following function to dynamically remove row from a table. This code is also tested on IE6 and FF2.

/**
 * Removes row of a table. Finds the table with table ID
 *
 * @param targetTableId - Table ID
 * @param targetRowIndex - index of the target row tobe removed
 * @param skipRows - Number of rows to be skipped
 */
 
function removeRow(targetTableId, targetRowIndex, skipRows)
{
     var targetTable = document.getElementById(targetTableId);
     var tableBody = targetTable.tBodies [0];
     var totalRows = tableBody.rows.length;
 
     if(totalRows == skipRows)
     {
          return false;
     }
 
     if(targetRowIndex == undefined || targetRowIndex == "")   
     {       
          targetRowIndex = totalRows - 1;   
     }    
    
     if(tableBody.hasChildNodes())   
     {
          tableBody.removeChild(tableBody.childNodes[targetRowIndex]);   
     }
}

Share/Save/Bookmark

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">