I'm trying to add a delete button to each item in a list. Adding them works as long as I don't have a delete button.
const newcontainer = document.getElementById("toDoContainers"); //gets number of list items in todolist //adds list item to list function deleteitem(paramitem){ var element = document.getElementById(paramitem); element.remove(paramitem); } function addnew(){ let numb = document.getElementById("todolistitems").childElementCount; var listitem = document.createElement("li"); var reallist = document.getElementById("todolistitems"); var inputvar = document.getElementById("inputfield").value; var node = document.createTextNode(inputvar); let numbvar = numb +1; listitem.appendChild(node); listitem.setAttribute('id', numbvar); listitem.addEventListener('onClick', deleteitem(listitem)); reallist.appendChild(listitem); var inputvar = document.getElementById("inputfield").value=""; // node.appendChild(document.createTextNode(inputvar)); /// document.getElementById("toDoContainers").innerHTML=inputvar; }
<h1>To Do List</h1> <div class="container"> <input id="inputfield" type="text"><button id="addToDo" onclick="addnew()">Add</button> <div class="tO" id="toDoContainers"> <ul id="todolistitems"> </ul> </div> </div>
I tried a method where on each list item you create you "onclick" = deleteitem(item). I have tried using queryselector, getelementbyId and queryselectorall in the delete function.
Adding list items works as long as I don't try to add delete functionality.
There are some errors in your code.
You need to wrap it in another function that returns a function to be executed on click and fix the error like this: