Javascript Delete A Table Tbody Tag
I know I can use the following code to remove rows in vanilla Javascript: But this code leaves an empty tbody tag behing. JS has methods for removing thead and tfoot elements, but
Solution 1:
Try using:
var tbl = document.getElementById("table"); // Get the table
tbl.removeChild(tbl.getElementsByTagName("tbody")[0]); // Remove first instance of body
Solution 2:
Use querySelectorAll()
to iterate through all TBODY
elements, then remove those that have no children:
var table = document.getElementById('table');
functiondeleteRow() {
table.deleteRow(1);
var tb = document.querySelectorAll('tbody');
for (var i = 0; i < tb.length; i++) {
if (tb[i].children.length === 0) {
tb[i].parentNode.removeChild(tb[i]);
}
}
};
table {
background: #ccc;
width: 100%;
}
tablethead {
background: #333;
color: #fff;
}
tabletbody {
background: magenta;
color: #fff;
}
<buttononclick="deleteRow()">Delete Row</button><tableid="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>
Solution 3:
If you want to remove the tbody
tag, you could select the row itself rather than the table, then use the removeChild
function.
var table = document.getElementById('table');
var row = document.getElementsByTagName('tbody')[0];
functiondeleteRow () {
row.parentNode.removeChild(row);
};
Solution 4:
There is no deleteTbody
but there is removeChild
:
var parent = document.getElementById("parent-id");
var child = document.getElementById("child-id");
parent.removeChild(child);
Post a Comment for "Javascript Delete A Table Tbody Tag"