beginner
beginner

Reputation: 5

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 increment 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();
  }
});

Upvotes: 0

Views: 260

Answers (2)

Max Tuzenko
Max Tuzenko

Reputation: 1358

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

Upvotes: 0

User456
User456

Reputation: 1301

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.

Upvotes: 0

Related Questions