How to empty table in javascript?

Viewed 3383

I cant delete the row contents of a table, but what if I want to delete the rows too?

My Javascript code: (I want all the rows to disappear except the first one.)

function deleteAll() {
        for ( var i = 0; i <= table.rows.length; i++){
            table.rows[i].cells[0].innerHTML = "";
            table.rows[i].cells[1].innerHTML = "";
            table.rows[i].cells[2].innerHTML = "";            
        }     
        
    }

My HTML table:

<body>
    <div class="container">
        <div class="tab tab-1">
            <table id="table" border="1">
                <th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Age</th>
                </th>
                <tr>
                    <td>Frank</td>
                    <td>Nenjim</td>
                    <td>19</td>
                </tr>
                <tr>
                    <td>Alex</td>
                    <td>Ferreira</td>
                    <td>23</td>
                </tr>


            </table>      

        </div>
        <div class="tab tab-2">
            First Name :<input type="text" name="fname" id="fname">
            Last Name :<input type="text" name="lname" id="lname">
            Age :<input type="number" name="age" id="age">

            <button onclick="deleteAll()">Delete All</button>

        </div>

    </div>
    <script src="tableEdit.js"></script>
</body>    

So, the Javascript code above doesn't satisfy me because I want only the first row to remain. I don't want empty rows.

3 Answers

You can use the jQuery remove() function as described in this example to delete all rows except the (first) header row:

$('#table tr:not(:first)').remove();

You may instead want to delete just the rows of body section (inside <tbody>) as mentioned in this post:

$('#table > tbody > tr').remove();
for(var i = 1;i<table.rows.length;){
            table.deleteRow(i);
        }

If you want to remove data rows only then use

$("#table tr").remove();

And if you want to empty table with header then use

$("#table").empty();
Related