- I am trying to make a to do list and right now when I press on the add task button 2 inputs and 1 select element are being created and displayed on the page.I save the content and display it and its just the nodelist string
Now I know querySelectorAll gives a nodeList and local storage only stores strings.
- How can I make the nodeList appear as the HTML elements and their values instead of the nodelist string?
- My broken code:
//Implementing local storage
document.addEventListener("DOMContentLoaded",function() {
//Save sct1taskTable into localStorage
sct1SaveToLocalStorageBtn.addEventListener("click",() => {
const taskTableContent = document.querySelectorAll(".task-table-child");
localStorage.setItem("taskTableContentKey",taskTableContent);
alert("Content saved :D");
})
//Retrieve sct1taskTable into localStorage
sct1LoadFromLocalStorageBtn.addEventListener("click",() => {
const loadedTaskTableContent = localStorage.getItem("taskTableContentKey");
sct1taskTable.innerHTML = loadedTaskTableContent;
alert("Content loaded :D")
})
});
2
Answers
You can change your approach. Your goal is to store the to-do list data and then restore it.This data doesn’t necessarily have to be HTML nodes; it can be an object. When you restore the nodes, use the stored object data to recreate the nodes.
document.querySelectorAll(".task-table-child")
will retrieve an array-like-object whose elements are all elements that match your selector of ".task-table-child" at the time you called it. To convert all these into HTML string, you could do something like this:I have queried your elements, converted the array-like-object into an actual array via the
[...<something here>]
operator and calledmap
on the array to replace theitem
s with theirouterHTML
(you could useinnerHTML
instead if you prefer) and then converted it into a string via.join("")
. So, you could do something likeLoading things back would look like
and then you can write this wherever you want.