0

I have added some key values pairs in local storage. Now I want to fetch both values and keys and append its values in li. I am trying to it like this right now.

for ( var i = 0; i < localStorage.length; ++i ) {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(localStorage.getItem(localStorage[key]) + "    " + localStorage.getItem(localStorage.key(i))));
    ol.appendChild(li);
}

I want an output key value pairs like:

key1 value1

key2 value2

0

1 Answer 1

1

You can use for...in to iterate over object indexes.

for (var key in localStorage) {
    var li = document.createElement("li"),
        value = localStorage.getItem(key);

    li.innerHTML = key + " " + value;
    ol.appendChild(li);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Make sure you put in a check for localStorage. If they're in incognito mode, it'll be undefined (or null?).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.