I have a list to add a class, but just items after add by input works with toggle. The items in the code don’t work.
I wonder if is something related to "this" property too.
Link to CodePen.
https://codepen.io/kennedyrmenezes/pen/BaQRXMq
li.addEventListener("click", function() {
var finished = this.classList.toggle("done");
var removeButton = document.createElement("button");
removeButton.classList.add("deleteButton");
if (finished) {
removeButton.appendChild(document.createTextNode("remove"));
removeButton.classList = "deleteButton";
li.appendChild(removeButton);
removeButton.addEventListener("click", function() {
this.parentElement.remove();
});
} else {
this.getElementsByClassName("deleteButton")[0].remove();
}
})
That because you only listen
click
event for only dymanic addedli
element.You should add event listenner for hard-code elements also. In example below I show a alert when click to
li
itemhttps://codepen.io/1412108/pen/OJbgJEW?editors=1010