1
I’m a Javascript beginner and I tried to make a To-Do List. Basically, it is a code that creates an item within an unordered list using the text inserted in an input. I was successful in the process of creating the list items, but I had the idea of creating a function that removes the items from the list, and that’s where the problem started. I tried to make it a "remove button" (in quotes because it is actually a tag with href="javascript:functionDemove()") for each item in the list (which when clicked would remove the item to which it is associated and itself)but what happens is that when I click on any remove button, always the last item is removed and the other remove buttons stop working.
My code:
HTML
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List:</h1>
<br>
<input type="text" placeholder="Insira aqui os seus afazeres" id="itemLista">
<button onclick="addTarefa()">Adicionar tarefa</button>
<br>
<ul id="ul">
</ul>
<script src="script.js"></script>
</body>
</html>
Javascript
var itemLista = document.getElementById("ul");
function addTarefa() {
if (document.getElementById("itemLista").value !== "") {
var tarefa = document.createElement("li");
tarefa.innerHTML = document.getElementById("itemLista").value;
itemLista.appendChild(tarefa);
document.getElementById("itemLista").value = "";
var remover = document.createElement("a");
window.removerTarefa = function () {
itemLista.removeChild(tarefa);
itemLista.removeChild(remover);
}
remover.innerHTML = "Remover";
remover.setAttribute("href", "javascript:removerTarefa()");
itemLista.appendChild(remover);
}
}
Thanks! When I went to sleep, I touched this problem of the superscript, and had even thought of a gambiarra with array to solve , but this way is much easier.
– Nathan Murillo