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

292
Views
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 answers
Answer question

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 Report

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 Report
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!