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
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")
})
});
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:
console.log([...document.querySelectorAll(".task-table-child")].map(item => item.outerHTML).join(""))
<div class="parent">
<div class="task-table-child"><p>something</p></div>
<div class="task-table-child"><p>something else</p></div>
</div>
I have queried your elements, converted the array-like-object into an actual array via the [...<something here>]
operator and called map
on the array to replace the item
s with their outerHTML
(you could use innerHTML
instead if you prefer) and then converted it into a string via .join("")
. So, you could do something like
localStorage.setItem("taskTableContentKey",[...document.querySelectorAll(".task-table-child")].map(item => item.outerHTML).join(""));
Loading things back would look like
const loadedTaskTableContent = localStorage.getItem("taskTableContentKey");
and then you can write this wherever you want.