Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda