Home › Forums › JavaScript › JS Add/Remove Row in Table › Reply To: JS Add/Remove Row in Table
August 27, 2013 at 7:44 am
#148229
Participant
Check out this pen I made: http://codepen.io/WillsonSmith/pen/cLktj
//Define your elements
var table = document.getElementById('theTable'),
// your parent element you are adding content to
rows = table.querySelectorAll('tr'),
//initial rows for counting
rowCount = rows.length,
//how many rows exist
addedRow = document.createElement('tr'),
//create the new row
addButton = document.getElementById('add'),
removeButton = document.getElementById('remove');
//basic buttons for example
function addRow(){
var thisRow = addedRow.cloneNode(true);
//clone your created row
thisRow.setAttribute('class','.pt-entry-' + rowCount);
//set the class to be class + the row count (will increment)
rowCount += 1;
//increment
thisRow.innerHTML = '<td>row</td>';
//adding whatever, not necessary
table.appendChild(thisRow);
//puts the row in to your parent
}
function removeRow(){
var items = table.querySelectorAll('tr');
//get the new list of rows
if (rowCount > 1){
table.removeChild(items[rowCount - 1]);
}
//remove the last item
rowCount -= 1;
//decrement
}
addButton.addEventListener('click', function(e){
addRow();
});
removeButton.addEventListener('click', function(e){
removeRow();
});
Since you’re only adding one element at a time, this is probably the way to do it. I didn’t look it over too much for optimisations because they would most likely be very small ones that really wouldn’t affect your code.
Note that if you were adding multiple items in to the dom at once, you would want to create a document fragment that you applied all of your added nodes to, and then apply the fragment to the page.
see: https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment
edit: added a check to make sure it’s not removing the last row