'How to place Local Storage on to the DOM - JavaScript
My problem I am having is when I loop through my local storage only the last item get place on the DOM when I want to place all items to do the DOM
function checkStorage() {
let cartContents = document.getElementsByClassName("products")[0];
let cartProduct = document.createElement("div");
cartProduct.classList.add("product");
let cartCheck = JSON.parse(localStorage.getItem("localItem"));
// return cartCheck;
savedCart = "";
if (cartCheck === null) {
return;
} else {
console.log(cartCheck);
for (const check in cartCheck) {
if (Object.hasOwnProperty.call(cartCheck, check)) {
const element = cartCheck[check];
savedCart = `<img width="60" src="${element.img}" alt="iphone" />
<div>
<span class='title'> ${element.title}</span>
<div class='price-section'>
<input type="number" value="1" class="cart-quantity-input" />
<span class='cart-price'>${element.price}</span>
</div>
</div>
<button class='btn-danger'>
<i class="bi bi-x"></i>
</button>`;
cartProduct.innerHTML = savedCart;
console.log(cartProduct);
cartContents.append(cartProduct);
}
}
}
}
Solution 1:[1]
You're updating the entire innerHTML of cartProduct for every iteration inside your for-loop. That's why only the last item gets put on the DOM.
Create an empty string outside the for-loop, and append HTML to that string for every iteration. Then update the innerHTML after your for-loop.
function checkStorage() {
let cartContents = document.getElementsByClassName("products")[0];
let cartProduct = document.createElement("div");
cartProduct.classList.add("product");
let cartCheck = JSON.parse(localStorage.getItem("localItem"));
// return cartCheck;
savedCart = "";
if (cartCheck === null) {
return;
} else {
console.log(cartCheck);
let savedCartsHtml = '';
for (const check in cartCheck) {
if (Object.hasOwnProperty.call(cartCheck, check)) {
const element = cartCheck[check];
savedCart = `<img width="60" src="${element.img}" alt="iphone" />
<div>
<span class='title'> ${element.title}</span>
<div class='price-section'>
<input type="number" value="1" class="cart-quantity-input" />
<span class='cart-price'>${element.price}</span>
</div>
</div>
<button class='btn-danger'>
<i class="bi bi-x"></i>
</button>`;
savedCartsHtml += savedCart;
console.log(cartProduct);
cartContents.append(cartProduct);
}
}
cartProduct.innerHTML = savedCartsHtml;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | timpa |
