I have successfully implemented a to-do list where clicking on an item strikes a line through it and there is a delete button that works. However, I am looking for assistance on how to create a delete button for each newly added li item.
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.getElementsByTagName("li");
var btn1 = document.getElementById("btn1");
ul.addEventListener("click", function(ev) {
if (ev.target.tagName === "LI") {
ev.target.classList.toggle('checked');
}
}, false);
function inputLength() {
return input.value.length;
}
function deleteBtn() {
var myList = document.getElementsByTagName("li");
for (var i = 0; i < myList.length; i++) {
deleteButton.onclick = this.parentElement.style.display = "none";
}
}
function createListElement() {
var myList = document.getElementsByTagName("li");
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
}
function addListAfterClick() {
if (inputLength() > 0) {
createListElement();
}
}
function addListAfterKeypress() {
if (inputLength() > 0 && event.keyCode === 13) {
createListElement();
}
}
btn1.addEventListener("click", deleteBtn);
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
ul li.checked {
text-decoration: line-through;
}
<input id="userinput" type="text" placeholder="enter list item here">
<button id="enter">Add</button>
<ul id="myUL">
<li>eggs</il><button id="btn1">delete</button>
<li>milk</li>
<li>tacos</li>
</ul>
In the deleteBtn function I tried adding
deleteButton = document.createElement("button");
deleteButton.appendChild.createTextNode("delete);
right after the for loop but I couldn't get it to work. I also tried adding it in the createListElement function and I couldn't get that to work either. Any help or suggestions would be greatly appreciated.