Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
How to prevent adding another SPAN element?

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 = "&times;";
    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>

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!