I know I can use the following code to remove rows in vanilla Javascript:
var table = document.getElementById('table');
function deleteRow () {
table.deleteRow(1);
};
table { background: #ccc; width: 100%; }
table thead { background: #333; color: #fff; }
table tbody { background: magenta; color: #fff; }
<button onclick="deleteRow()">Delete Row</button>
<table id="table">
<thead>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</thead>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
</table>
But this code leaves an empty tbody tag behing. JS has methods for removing thead and tfoot elements, but it seems it's missing a deleteTbody
one.
How am I supposed to remove a tbody
and all it's contents by using pure javascript only? No jQuery, please!
The <tbody> tag is used to group the body content in an HTML table. The <tbody> element is used in conjunction with the <thead> and <tfoot> elements to specify each part of a table (body, header, footer). Browsers can use these elements to enable scrolling of the table body independently of the header and footer.
This can be done by using JavaScript. First of all set the ID or unique class to the table. Select the table element and use remove() or detach() method to delete the all table rows.
You may use more than one <tbody> per table as long as they are all consecutive. This lets you divide the rows in large tables into sections, each of which may be separately formatted if so desired.
The remove() method is used to remove the table row from an HTML table using JavaScript. remove() Method: This method removes the selected elements alongwith text and child nodes. This method also removes data and events of the selected elements.
Try using:
var tbl = document.getElementById("table"); // Get the table
tbl.removeChild(tbl.getElementsByTagName("tbody")[0]); // Remove first instance of body
https://jsfiddle.net/Ltdr2qv4/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With