Javascript get the last td of a table to remove/delete it

Viewed 37

How can I get the last td of a table and remove it? It should be only JS, no jquery.

I tried this:

e.target.parentNode.querySelector("td:lastcell").remove();
2 Answers

var t = document.getElementById("test"); // The table
var lastTD = t.querySelector("TD:last-of-type");
console.log ("Text: " + lastTD.innerText);
<table id="test">
<tr>
<td>A</td>
<td>B</td>
</tr>
</table>

element.children should get you all the children as an array you can get the last child simply by element.children[element.children.length -1] and do whatever you want with it. Also if your table has an id you can get the last td by using document.querySelect('#table-id td:last-child') or use document.querySelectAll('#table-id td:last-child') to get all the last tds

Related