I created a CRUD page and in an input when the user types a text that text gets added in a list. now i want to save that list in localStorage and i tried to store it but I'm getting an empty object in the console log. any help would be appreciated.
JAVASCRIPT
const addItem = function() {
let val = input.value;
if (val) {
let li = document.createElement('li');
let inner = '<h1 class="text">' + val + '</h1>';
inner += '<button class="delete">Delete</button>';
inner += '<button class="edit">Edit</button>';
li.innerHTML = inner;
container.appendChild(li);
input.value = '';
currentItem = li.firstChild;
//i want to save the below list
items = document.querySelectorAll('li');
for(let item of items){
//this return empty object
localStorage.setItem('list', JSON.stringify(item) );
console.log(localStorage)
}
for (let del of document.querySelectorAll('.delete')) {
del.addEventListener('click', deleteItem);
}
for (let edit of document.querySelectorAll('.edit')) {
edit.addEventListener('click', editItem);
}
} else {
alert('please add some text');
return;
}
}
HTML if needed
<div class="main">
<h2>JavaScript CRUD Bookmark</h2>
<form>
<input type="text" placeholder="search">
</form>
<ul></ul>
<div>
<input class="add-text" type="text" placeholder="Add Text">
<button id="add">Add</button>
<button id="update">update</button>
</div>
</div>
You should be saving the value of the form fields, rather than DOM elements themselves, as others have commented as well. However, you could do something like this if you need to store DOM elements.
localStorage.setItem('list', JSON.stringify(item.outerHTML))
Later, you'd have to re-create the DOM element, using something like this:
let div = document.createElement('div');
div.innerHTML = JSON.parse(localStorage.getItem('list'))
Also, the for loop you have for items
is overwriting the localStorage item value each time. If you want to create unique items in localStorage, consider adding a unique identifier to the item key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With