first of all, super beginner here. I'm trying to do a to do list. The add part works fine, it looks like this:
let salvar = document.getElementById("salvar")
let remove = document.getElementById("remover")
salvar.onclick = saveitem
function saveitem() {
let item = document.getElementById("input").value
let novoitem = document.createElement("tr")
let lista = document.getElementById("todoitems")
novoitem.innerText = item
lista.appendChild(novoitem)
}
<input type="text" id="input">
<div class="container">
<button id="salvar">Save</button>
<button id="remover">Remove</button>
</div>
<table id="todoitems">
<tr>
<th>Tarefa</th>
</tr>
</table>
How can i create a function that removes the last added item?
First of all we need to use correct markup for your table. tr must be a child of either thead or tbody. Secondly, you cannot have text nodes as children of tr; these must be placed in td or th elements. Also it's bad practice to use non-English variable names, I've changed that to English.
That being said, here's your solution:
let add = document.getElementById("add")
let remove = document.getElementById("remove")
remove.onclick = removeLastItem;
add.onclick = saveitem;
function saveitem() {
let item = document.getElementById("input").value;
let newRow = document.createElement("tr");
let list = document.getElementById("todoitems");
newRow.innerHTML = `<td>${item}</d>`;
list.appendChild(newRow);
}
function removeLastItem() {
document.querySelector('#todoitems tr:last-child')?.remove();
}
<input type="text" id="input">
<div class="container">
<button id="add">Save</button>
<button id="remove">Remove</button>
</div>
<table>
<thead>
<tr>
<th>Tarefa</th>
</tr>
</thead>
<tbody id="todoitems"></tbody>
</table>
Explanation of the removeLastItem() function:
document.querySelector('#todoitems tr:last-child')?.remove()
querySelector allows you to pass in a CSS selector that works just like it does in CSS. To select the last tr in the tbody#todoitems you use #todoitems tr:last-child as your CSS selector. The ? is the safe navigator/optional chaining that makes sure your code doesn't throw an error if someone clicks the remove button when there are no items in your table.
document.getElementById('todoitems').lastChild.remove()
use last child property
instead of using remove button you can add button inside tr and when pressed it can delete the that tr for you
function saveitem(){
let item = document.getElementById("input").value
let novoitem = document.createElement("tr")
let delBtn = document.createElement("button")
delBtn.innerText = "del"
delBtn.addEventListener("click",function(){
novoitem.remove();
})
let lista = document.getElementById("todoitems")
novoitem.innerText = item
lista.appendChild(novoitem)
novoitem.append(delBtn);
}