Search code examples
javascripthtmlobjectcookiesnodelist

What does it mean by [Object Nodelist]?


i was working on a todo simple html webpage and there i have added a button which selects all of the added task on that webpage and adds it the user's cookies,

document.getElementById("save-all-btn").addEventListener("click", function(e) {
    let elements = document.querySelectorAll("li");

    setCookie("taskList", elements, 30);
    let Value = getCookie("taskList");
    console.log(Value);
});

Just like in above code i have a event listener which runs a function on my button click and this function then selects all the "Li" on my webpage and then i have a function which i just simply use to set the cookie name, value & it's expiry, after then i have a variable in which a return value is stored from a function called getCookie which simple just reads the user cookie by the cookie name

But When i use console.log on my returned value it shows me [object NodeList]

and i am confused what it is and is there any way to save nodelist in cookies and then load it back as nodelists and append it to my HTML File

My setCookie & getCookie functions look like these:

function setCookie(cname, cvalue, exdays) {
    const d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    let expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    let name = cname + "=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for(let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

this piece of code i got from Here


Solution

  • Here is an excerpt which explain the difference between an Array and NodeList:

    NodeLists and Arrays are two different things because NodeLists are actually not a JavaScript API, but a browser API.

    Things like querySelectorAll() and getElementsByTagName() aren’t JavaScript methods, they’re browser APIs that let you access DOM elements. You can then manipulate them with JavaScript.

    (source)

    Having said that, there is no one-to-one conversion between Node List and Array in such a way that the resultant array is going to contain all the properties and methods which it has in the context of the Browser API.

    You can query the nodes, and save some of the important properties of them such as their dimensions, data etc in a textual format (like json). You will have to read this text back and create the nodelist yourself via the DOM methods.