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

293
Visualizações
The elements are being duplicated when adding them to container from local storage

I want to add some values to a container and save them in localstorage but when I click on the button to add them after the first time elements are being duplicated in the container, not the localstorage.

The weird thing is that when I reload the page the duplicates go out and the elements increament by the count of elements I added only here's my code:

    let divP = document.querySelector(".parent");
    let input = document.querySelector("input");
    let button = document.querySelector("button");
    let container = document.getElementById("container");
    
    let array = JSON.parse(localStorage.getItem("array")) || [];
    let isUpdate = false;
    
    function createElement() {
      array.forEach((arr, id) => {
        let div = document.createElement("div");
        div.classList.add("div");
        div.id = id;
        div.innerHTML = arr.title;
        container.appendChild(div);
      });
    }
    createElement();
    
    button.addEventListener("click", (e) => {
      e.preventDefault();
      let title = input.value.trim();
      let id = Date.now();
      if (title || id) {
        let arrayInfo = { title, id };
        if (!isUpdate) {
          array.push(arrayInfo);
        } else {
          isUpdate = false;
        }
        localStorage.setItem("array", JSON.stringify(array));
        createElement();
      }
    });
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can clear the divs like this:

function createElement() {
  const divs = document.querySelector('.div');
  divs.forEach((div) => {
    div.remove();
  });
  array.forEach((arr, id) => {
    let div = document.createElement("div");
    div.classList.add("div");
    div.id = id;
    div.innerHTML = arr.title;
    container.appendChild(div);
  });
}

Note that it will clear all the elements with the class div.

about 4 years ago · Juan Pablo Isaza Relatório

0

Bear in mind that every time you execute "createElement" you add all elements of the array to the dom. So elements keep accumulating without a way out. To solve this you need to flush all previous divs, just add line below as first line of function createElement() :

container.innerHTML = "";
about 4 years ago · Juan Pablo Isaza Relatório
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