Reputation: 21
I am trying to add delete button to each item in a list. Adding them works as long as I do not have the 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 thing where on each list item created, you can 'onclick'=deleteitem(item). I have tried using queryselector, getelementbyId, and queryselectorall in the delete function.
Adding list items works as long as I do not try adding the delete functionality.
Upvotes: 1
Views: 414
Reputation: 68
There's a few errors in your code.
You need to wrap this in another function that returns the function to be performed on click, and fix that error, as below:
const newcontainer = document.getElementById("toDoContainers");
//gets number of list items in todolist
//adds list item to list
function deleteitem(paramitem) {
var element = document.getElementById("list" + paramitem);
element.remove();
}
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", "list" + numbvar);
listitem.addEventListener("click", function () {
deleteitem(numbvar);
});
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>
Upvotes: 2