Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to delete all table rows except first one using jQuery?

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

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.

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;">
            neveropen
        </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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments