0

I am a complete newbie and apologize for such question in advance. What is the most optimal way of getting my localStorage to display in a div? Let's say I'll keep only the ".first" and I want to put all keys into it.

Here is my desired result, but of course I need to shorten this.

function myFunction() {
  document.querySelector('.first').innerHTML = (localStorage.key(i))
  document.querySelector('.second').innerHTML = localStorage.key(2)
  document.querySelector('.third').innerHTML = localStorage.key(3)
}

I'm trying with:

function myFunction() {
  document.querySelector('.first').innerHTML = (localStorage.key(i))
  for ( var i = 0; i < localStorage.length; ++i ) { 
    console.log(localStorage.key(i)+ 
    localStorage.getItem(localStorage.key(i))); 
  }
}

Where do I attach the result from the loop (most likely multiple pieces of text) to be lined up in the div?

lisenigen
  • 1
  • 3
  • 1
    Does this answer your question? [Get HTML5 localStorage keys](https://stackoverflow.com/questions/8419354/get-html5-localstorage-keys) – hackape Oct 31 '20 at 14:06

2 Answers2

0

There're several ways to do that At first you shouldn't select elements in document using classes because several items in DOM can have same class. Use ID instead.

You can attach paragraph every each loop (very time consuming option).

function myFunction() {
  for ( var i = 0; i < localStorage.length; ++i ) { 
    const p = document.createElement("p");
    p.innerHtml = localStorage.getItem(localStorage.key(i));
    document.querySelector('.first').appendChild(p);
  }
}

You can first generate innerHTML string and then attach it to innerHTML

let localStorageItems = '';
function myFunction() {
  for ( var i = 0; i < localStorage.length; ++i ) { 
    localStorageItems += `<p>${localStorage.getItem(localStorage.key(i))}</p>`
  }
  document.querySelector('.first').innerHTML = localStorageItems;
}
Igor Nowosad
  • 529
  • 3
  • 9
0

You can get all the keys to the div by using the following

document.querySelector('#first').innerHTML = Object.keys(localStorage);