Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to delete all table rows except first one using jQuery?

  • Last Updated : 09 Feb, 2021

Given an HTML document containing an HTML table and the task is to delete the table row except the first one using jQuery.

Approach: First, we create a table using <table> tag and add a button containing btn id. When a user clicks on the button, then the jQuery function is called. The jQuery function removes all the rows except the first one using the remove() method.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Syntax:

$('#btn').click(function () {
    $("#rTable").find("tr:gt(0)").remove();
});

Example:

HTML




<!DOCTYPE HTML>
<html>
  
<head>
    <meta http-equiv="Content-Type" 
        content="text/html; charset=utf-8">
         
    </script>
  
    <style>
        table,
        th,
        td {
            border: 1px solid black;
            border-collapse: collapse;
        }
  
        th,
        td {
            padding: 20px;
        }
    </style>
  
    <script>
        $(document).ready(function () {
            $('#btn').click(function () {
                $("#rTable").find("tr:gt(0)").remove();
            });
        });
    </script>
</head>
  
<body>
    <center>
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
  
        <h4>
            Delete all table rows except
            first one using jQuery
        </h4>
  
        <table style="width:50%" id="rTable">
            <tr>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Age</th>
            </tr>
            <tr>
                <td>Priya</td>
                <td>Sharma</td>
                <td>24</td>
            </tr>
            <tr>
                <td>Arun</td>
                <td>Singh</td>
                <td>32</td>
            </tr>
            <tr>
                <td>Sam</td>
                <td>Watson</td>
                <td>41</td>
            </tr>
        </table>
        <br><br>
  
        <button id="btn">
            Remove All Row Except First One
        </button>
    </center>
</body>
  
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!