New to Rust? Grab our free Rust for Beginners eBook Get it free →
Dynamically Add and Remove HTML Table Rows

To make an HTML table respond to changes after a page loads, you can update its rows with JavaScript. JavaScript inserts or removes rows in the page’s DOM without rebuilding the whole page.
I’ll show how to add a row and remove the row containing the clicked button.
TL;DR: Add and Remove Table Rows
Use insertRow() to add a row to a tbody, remove a selected row with row.remove(), and clear data with tbody.replaceChildren().
- Keep headings inside thead and editable records inside tbody.
- Listen for remove clicks on the body so the handler also works for rows added later.
- Put user-entered values into cells with textContent, not HTML parsing.
What Is a Dynamic HTML Table?
A dynamic HTML table is a table whose rows change after the page loads, usually in response to a user’s action or new data. JavaScript reaches the table elements through the DOM and inserts or removes nodes without rebuilding the whole page.
| Element or method | Role in this example |
|---|---|
| thead | Column labels that remain in place |
| tbody | Data rows that can change |
| insertRow() | Creates and inserts a table row |
| remove() | Removes the selected row element |
| replaceChildren() | Clears body contents in one operation |
How to Add and Remove Table Rows Step by Step
This example adds a Coffee row, removes a row through its own button, and clears remaining body rows while preserving the header.
Step 1: Mark up the table and its controls
Give the table a stable ID with explicit sections. The Add button goes outside the table, and the starter data row gets its own remove control.
<table id="items">
<thead><tr><th>Name</th><th>Action</th></tr></thead>
<tbody>
<tr><td>Tea</td><td><button class="remove" type="button">Remove</button></td></tr>
</tbody>
</table>
<button id="add" type="button">Add</button>
The type=”button” attribute prevents either control from submitting a surrounding form.
Table headings should use header cells so assistive technology can associate each data value with its column.
Place the Add button after the table in the markup, as shown above.
Step 2: Add a row and put its values in cells
Select the body once and call insertRow() on it. Create cells in the needed order, then assign plain text and build the button as an element.
const body = document.querySelector('#items tbody');
const addButton = document.querySelector('#add');
addButton.addEventListener('click', () => {
const row = body.insertRow();
row.insertCell().textContent = 'Coffee';
const action = row.insertCell();
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'remove';
remove.textContent = 'Remove';
action.append(remove);
});
Step 3: Remove the row that owns the clicked button
Attach a listener to the table body and identify remove-button clicks.
body.addEventListener('click', event => {
if (event.target.matches('.remove')) {
event.target.closest('tr').remove();
}
});
closest(‘tr’) walks from the clicked button to its containing row.
Step 4: Clear the body but retain the headings
The terminal output states the final count directly.
After add: Tea, Coffee After remove: 1 data row After clear: 0 data rows; header: Name

For a clear result, remove children in a loop while the body has a first child. This works because each removal changes the DOM before the next condition is checked.
Edge Cases When Changing Table Rows
Row bugs often come from selecting the wrong part of a table or relying on an index after the collection changes. The table below pairs common cases with their cause and response.
| Case | What happens | Response |
|---|---|---|
| Empty body | A clear operation has no rows to remove | Clearing an empty body is a no-op |
| Missing selector | querySelector() returns null and a method call throws | Check the result before calling insertRow() or another method |
| Header shares the body | A loop over every row may erase a label row too | Place labels in thead and clear only tbody |
| Forward deletion by index | Rows shift left after each deletion, so the next index can skip a row | Delete from the last index backward or clear the body |
| User text inserted as markup | HTML strings are parsed as elements | Use textContent for plain values |
The empty-body probe returned empty tbody rows: 0. A probe of a missing body returned TypeError: Cannot read properties of null (reading ‘replaceChildren’). Check the selector result before calling a method on it.
Cloning an existing row can copy IDs, values and inline handlers along with its inputs.
When a value comes from a form, assign it to textContent to display it as text. innerHTML parses a string as markup, so reserve it for trusted markup.
For instance, a product name such as <script> should appear as typed text in a cell. Create the fixed Remove button with createElement() and append it separately, rather than mixing that control into a value string.
If removal takes focus away with the deleted button, move focus to the next row control or the Add button so keyboard users can continue.
For a dedicated example of removing one existing row, see how to remove a row from a table with JavaScript. When a later task needs to convert a selected node list, CodeForGeek also explains converting a JavaScript NodeList to an array.
A product table can use Product, Price, and Action columns. It needs Add a Product and Delete a Product controls. “Recommended Answers” and “Dani AI” are ordinary sample values when they appear in application data.
Read each field before adding a product.
Name its Delete button for the product, and let the click handler find the containing row.
An empty inventory still needs a clear next action. Keep Add a Product available when there are no records, and make a clear-all action distinct from deleting one product because it affects every current record.
For a product list, the Add a Product action usually reads several fields, not one label. Keep each input associated with a clear label, then gather the values into named variables before building a row.
For a row with a quantity field, set the input type and accessible label deliberately, then read its current value when the user submits an edit.
A Clear table button should say what it affects.
Check that an added product appears under the intended headings and that removing it leaves adjacent records intact. Clear the body afterward, then confirm the header remains.
Test an empty body, which should remain empty after clearing. A missing table or body returns null from querySelector(), so handle that setup problem before calling insertRow() or replaceChildren().
Use Tab to reach Add and activate it, then test a row’s Delete button. Check that focus moves somewhere useful after removal. Give each button a specific accessible name because repeated “Delete” labels offer little context in assistive technology.
A clear summary helps when several operations share the same page. Keep each control’s event handler and confirmation behavior aligned with its target.
An edit form should make the selected product clear before the user changes a field.
Data attributes offer one way to associate a rendered row with a key. A row can carry a data-product-id value, and a handler can read it from the containing row before making an API request.
For a server-backed table, show when a request is pending. If it fails, restore the control and say whether the row stayed unchanged.
A server may return normalized values, such as a formatted price. Render its returned values when it owns the record.
A confirmation can name the product added or removed. An error can identify the failed operation.
When editing several product fields, build the change from a submitted form rather than reading arbitrary page text.
After an edit succeeds, update only the matching row or rerender the list from its data array.
When the application keeps products in an array, update the matching object before rendering its row again. Use a stable property such as an ID to find that object. An array index may work for a short local example, but it is fragile once users sort or filter the list.
A render function can accept a list and create each row from its current data. That gives the page one repeatable way to draw initial records and later changes. Keep event handling on a parent that remains in the document, or attach handlers as each control is created.
Updating one row in place avoids replacing unaffected controls. If you instead rebuild the body, recreate its buttons and inputs too, since removed elements no longer respond to their old listeners. Test the chosen update path after adding, editing, deleting, and sorting a record.
For asynchronous requests, handle the returned promise in both success and failure paths.
When displaying an empty list, use a deliberate empty-state message instead of leaving users to guess whether data has loaded.
Consider how numeric values are stored before formatting them for display. Keep the underlying price as a number, then format it when rendering the cell. This lets sorting and totals use numeric comparisons rather than comparing strings that happen to contain currency symbols.
When a row contains a checkbox or select menu, read its current control value rather than assuming the original markup still describes the user’s choice. On edit, update both the application record and the rendered control state so the next operation starts from the accepted value.
For keyboard operation, confirm that each button can be reached and activated without a mouse. This makes the interaction predictable when rows change dynamically.
Conclusion
For method details, consult MDN’s insertRow(), deleteRow() and innerHTML references.
FAQ
These answers cover common details when a table must change after a click.
How do I add a row to an HTML table with JavaScript?
Select the table’s tbody and call tbody.insertRow(). Add cells with row.insertCell(), then set each cell’s textContent or append the required elements.
How can I remove all rows without deleting the table header?
Put headings in thead and data rows in tbody, then clear only the tbody, for example with tbody.replaceChildren().
Why does a row deletion loop skip rows?
Deleting a row shifts later rows to lower indexes. Iterate backward from the last row, or clear the tbody instead of deleting forward by index.




