-2

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();
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Rannaery
  • 39
  • 6
  • 2
    What have you tried so far? What about that attempt failed? – mykaf Sep 07 '22 at 16:36
  • Hi, welcome to SO. Please do read the [tour] and [ask]. – freedomn-m Sep 07 '22 at 16:40
  • e.target.parentNode.querySelector("td:lastcell").remove(); – Rannaery Sep 07 '22 at 16:40
  • So what exactly is `e.target`? If it's a not a `td` (eg a div in a td or button/input) then `.parentNode` will not give you the tr. – freedomn-m Sep 07 '22 at 16:42
  • `:lastcell` is not a valid pseudo-class, as far as I know. – mykaf Sep 07 '22 at 16:43
  • Rather than `:lastcell` (which doesn't appear to be a valid selector) - you can use `td:last-of-type` or `td:last-child`. But this will depend on whether you start at the table or tr. – freedomn-m Sep 07 '22 at 16:44
  • Does this answer your question? [Styling the last td in a table with css](https://stackoverflow.com/questions/359821/styling-the-last-td-in-a-table-with-css) – freedomn-m Sep 07 '22 at 16:46
  • I have a cancel Button and I want to remove the last td, when you click on them, but lastcell and last-type-of doesnt work. Here the code: – Rannaery Sep 07 '22 at 16:51
  • Are you sure it's the last-of-type not working and not the `e.target.parentNode`? Need more context/HTML. – freedomn-m Sep 07 '22 at 17:02

2 Answers2

1

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>
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

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

LHDi
  • 319
  • 1
  • 8
  • It removes the first td not the last by mine. Here the code: marksContainer.querySelector("button.cancel-mark").addEventListener("click", (e) => { e.target.parentNode.querySelector("table td:last-child").remove(); – Rannaery Sep 07 '22 at 16:44
  • It's vague what you've posted with element.children. But if this is on a table, this is going to get you the last row, not the last cell. Also, if the table has a TBODY / THEAD, doing element.children is a brittle solution – ControlAltDel Sep 07 '22 at 16:45