I'm struggling with a to-do app. I want to cross out a LI element and add a span with an x sign. It's easy by toggling class. However, when I "untoggle" the class by clicking again. The "x" remains and when I click on the item again the "x" is duplicated. How can I prevent adding another "x" or make the "x" disappear when the items is "untoggled".
const addButton = document.querySelector("#add");
const input = document.querySelector("input[name='input-item'");
const ul = document.querySelector("ul");
const allItems = document.querySelectorAll("li");
for (let i = 0; i < allItems.length; i++) {
allItems[i].addEventListener("click", myList);
}
function myList() {
let temp = this.classList.toggle("red");
if (temp) {
let span = document.createElement("span");
span.innerHTML = "×";
span.addEventListener("click", function() {
this.parentElement.remove();
});
this.appendChild(span);
} else if (this.classList.contains("red")) {
this.getElementByTagName("span").remove();
}
}
.red {
text-decoration: line-through;
color: red;
}
span {
background-color: white;
padding: 0 0.3rem;
color: black;
margin: 0 0.2rem;
display: inline-block;
}
<div class="container">
<ul>
<li>banana</li>
<li>orange</li>
<li>grapes</li>
</ul>
<input type="text" name="input-item" placeholder="Enter a new item" /><button id="add">Add Item</button>
</div>