Delete (Remove) all rows from Table except First (Header) row using jQuery

,

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.

Html

<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" /> 


jQuery


<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>

CSS


body
{
 font-family: Arial;
 font-size: 10pt;
}
table
{
 border: 1px solid #ccc;
 border-collapse: collapse;
 background-color: #fff;
}
table th
{
 background-color: #B8DBFD;
 color: #333;
 font-weight: bold;
}
table th, table td
{
 padding: 5px;
 border: 1px solid #ccc;
}
table, table table td
{
 border: 0px solid #ccc;
}





Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.