Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda