In this article I will explain with an example, how to delete
(remove) all rows from an HTML Table except First (Header) row using jQuery.
Delete all rows from Table except First (Header) row using jQuery
The following HTML Markup consists of an HTML Table with a Header row and three other rows and a Button. The Button has been assigned a jQuery OnClick event handler.
When the Button is clicked, all the TR (Table Row) elements except the First (Header) row are selected and then removed using the jQuery remove function.
<table id="tblCustomers" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<th style="width: 90px">Customer Id</th>
<th style="width: 120px">Name</th>
<th style="width: 90px">Country</th>
</tr>
<tr>
<td>1</td>
<td>John Hammond</td>
<td>United States</td>
</tr>
<tr>
<td>2</td>
<td>Mudassar Khan</td>
<td>India</td>
</tr>
<tr>
<td>3</td>
<td>Suzanne Mathews</td>
<td>France</td>
</tr>
<tr>
<td>4</td>
<td>Robert Schidner</td>
<td>Russia</td>
</tr>
</tbody>
</table>
<hr />
<input type="button" id="btnDelete" value="Delete Rows" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnDelete").click(function () {
$("#tblCustomers").find("tr:not(:first)").remove();
});
});
</script>
Screenshot
Browser Compatibility
The
above code has been tested in the following browsers.
* All
browser logos displayed above are property of their respective owners.
Demo
Downloads