Check this simple table:
const table = document.getElementById("table");
table.addEventListener('click', e => {
if (e.target.tagName === 'BUTTON') {
const affectedRow = e.target.closest('tr');
table.removeChild(affectedRow);
}
});
<table border="1" id="table">
<tr>
<td>row A</td>
<td><button>delete row</button></td>
</tr>
<tr>
<td>row B</td>
<td><button>delete row</button></td>
</tr>
<tr>
<td>row C</td>
<td><button>delete row</button></td>
</tr>
</table>
Trying to remove a row using table.removeChild(affectedRow)
gives me
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
Is using a tbody
element mandatory?
Why are browsers auto-inserting a tbody
element? I checked on validator.w3.org and omitting a tbody
tag seems valid HTML.
How do I remove the row without using HTMLTableElement.prototype.deleteRow(index)
, using only HTMLElement.prototype
methods and properties?