I have a table. At the end of each row tehere is a href “X” which deletes this row. This is pretty simple. Now when you click “X” for any row 2 it deletes row 2, but then when you click on row 3 it deleted row 4.
This is my code:
HTML
<table id="my_table" align="center" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>Custom0</td>
<td><a title="my title text" id="1" href="#" class="someclass" onclick="deleteRows(0)">X</a>
</td>
</tr>
<tr>
<td>Custom1</td>
<td> <a title="my title text" id="2" href="#" class="someclass" onclick="deleteRows(1)">X</a>
</td>
</tr>
<tr>
<td>Custom2</td>
<td> <a title="my title text" id="3" href="#" class="someclass" onclick="deleteRows(2)">X</a>
</td>
</tr>
<tr>
<td>Custom3</td>
<td> <a title="my title text" id="4" href="#" class="someclass" onclick="deleteRows(3)">X</a>
</td>
</tr>
<tr>
<td>Custom4</td>
<td> <a title="my title text" id="5" href="#" class="someclass" onclick="deleteRows(4)">X</a>
</td>
</tr>
<tr>
<td>Custom5</td>
<td> <a title="my title text" id="6" href="#" class="someclass" onclick="deleteRows(5)">X</a>
</td>
</tr>
</table>
and Javascript
function deleteRows(row) {
var tbl = document.getElementById('my_table'); // table reference
tbl.deleteRow(row);
}
You can play wit it here: http://jsfiddle.net/nTJtv/13/
You have hard-coded the row numbers, so after the first deletion they are out of sync. The
<table>element’s.rowsproperty is “live”, so removing one means the numbers no longer line up with your HTML.Instead, consider passing
this.parentNode.parentNodeto the function and using it to determine which row to delete:Then use
removeChild()in the function:Edit: The
<tr>is a child of the<tbody>element, so that must be the parent from which it is removed.http://jsfiddle.net/nTJtv/19/
If you would really rather do it with
deleteRow(), then loop through the rows to find the one passed to the function and delete it:http://jsfiddle.net/nTJtv/21/