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();
}
});
CodePudding user response:
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
.
CodePudding user response:
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 = "";