Reputation: 51
I am trying to make a To-Do List. When I am trying to remove the I am not able to do it at all. I don't know how to run function removeBtn()
var input = document.getElementById("task");
var button = document.getElementById("enter");
var ul = document.querySelector("ul");
function newElement(){
var node = document.createElement("li");
node.appendChild(document.createTextNode(input.value));
var delButton = document.createElement("button");
delButton.innerHTML = 'Done';
node.appendChild(delButton);
delButton.addEventListener('click', removeBtn);
ul.appendChild(node).classList.add("remList");
input.value ='';
}
function checkLength(){
if (input.value.length != 0){
newElement();
}
else {
alert('Empty');
}
}
function removeBtn(){
var list = document.getElementsByClassName("remList");
ul.removeChild("remList");
}
button.addEventListener("click", checkLength);
Upvotes: 1
Views: 45
Reputation: 370679
In addition to selecting a single element to remove, you need to tie the correct .remList
to be removed with the button listener. If you want the created node
to be removed when the delButton
is clicked, you need to connect node
to the listener somehow. One option is:
// ...
node.appendChild(delButton);
delButton.addEventListener('click', () => node.remove());
ul.appendChild(node).classList.add("remList");
// ...
(no need for a separate removeBtn
function at all)
Upvotes: 1
Reputation: 42304
document.getElementsByClassName()
returns a NodeList collection of elements. If you want to remove an individual one, you can access the collection like an array:
var list = document.getElementsByClassName("remList");
ul.removeChild(list[0]); // Remove the first `.remList` child
Upvotes: 0