I wouldn’t be storing div
elements at all, since people won’t be buying div
elements from you and there’s no reason to bloat up localStorage
with data and UI layer content. Instead, store the data that those elements contain and later, when you need to get that data out of storage, you can create div
elements (or any UI) to hold them for display on the page.
Here’s an example that shows why it’s better to not store the presentation with the data. I’ll show you that I can create two different presentations from one set of data (it won’t work here in the Stack Overflow snippet environment, but it will here in this Fiddle):
let cart = [];
const list = document.querySelector("select");
document.querySelector("button").addEventListener("click", function(){
cart.push(list.value); // Update the cart
localStorage.setItem("cart", JSON.stringify(cart)); // store cart
console.log(localStorage.getItem("cart"));
});
document.querySelector("#show").addEventListener("click", function(){
// Presentation #1
// Loop over all the items in the array that is created by
// converting the JSON in local storage to an array
JSON.parse(localStorage.getItem("cart")).forEach(function(item){
let row = document.createElement("div"); // make a div for the item
row.textContent = item; // populate the div
document.body.appendChild(row); // Put item in doc.
});
// Presentation #2
// Same data and same technique to access it
let tbl = document.createElement("table");
JSON.parse(localStorage.getItem("cart")).forEach(function(item){
// But different presentation
let row = document.createElement("tr");
let cell = document.createElement("td");
cell.textContent = item; // populate the div
row.appendChild(cell);
tbl.appendChild(row);
});
document.body.appendChild(tbl); // Put item in doc.
});
table, td {
border:1px solid grey;
border-collapse:collapse;
}
<select>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
<option>Item 4</option>
<option>Item 5</option>
<option>Item 6</option>
</select>
<button>Add to cart</button>
<button id="show">Show Cart</button>