Categories
JavaScript Answers

How to delete all rows in an HTML table with JavaScript?

Spread the love

You can delete all rows in an HTML table by removing the rows one by one until there are no rows left.

For example, we write:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete All Rows in Table</title>
</head>
<body>

<table id="myTable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>John Doe</td>
            <td>john@example.com</td>
        </tr>
        <tr>
            <td>Jane Doe</td>
            <td>jane@example.com</td>
        </tr>
        <!-- Add more rows as needed -->
    </tbody>
</table>

<button onclick="deleteAllRows()">Delete All Rows</button>

<script>
function deleteAllRows() {
    var table = document.getElementById('myTable');
    var rowCount = table.rows.length;
    
    // Start deleting from the last row to avoid skipping rows
    for (var i = rowCount - 1; i > 0; i--) {
        table.deleteRow(i);
    }
}
</script>

</body>
</html>

In this example, we have an HTML table with some sample rows and a button labeled “Delete All Rows”.

When the button is clicked, the deleteAllRows function is called.

Inside the deleteAllRows function, we get a reference to the table using getElementById.

We then get the total number of rows in the table using table.rows.length.

We loop through the rows starting from the last row (to avoid skipping rows due to index shifting) and delete each row using deleteRow(i).

This will effectively delete all rows from the table, leaving only the header row intact. Adjust the selector #myTable to match the id of your table.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *