0

I have found this article helpful: HTML5 localStorage: check if item is set

But, I can't find a solution, to the following issue.

A want to use 8 localStorage variables: names0, names1, names2 ... etc... names7

Then when a page loads, check to see they have been used, then show up to 8 -divs- accessed through the variable if so .

var cs = document.getElementsByClassName("classSelect");

for (i = 0; i < 8; i++) {
if (localStorage.getItem("names" + i) !== null) {
    alert("worked " + i);
    cs[i].style.display = "block";
}

I'm note sure how to achieve this.

Community
  • 1
  • 1
Russell
  • 655
  • 2
  • 9
  • 21
  • I don't know if you noticed because of your lack of indentation but you're missing the last `}`. – Denys Séguret Jun 12 '13 at 19:01
  • Thanks - was a copy/paste blunder. – Russell Jun 12 '13 at 19:03
  • Wayne makes a good point; though the OP's original method may be simpler if the values are set at various times in the program (otherwise you'd have to load them, modify them, and then set them). Also, localStorage may only allow for strings, so you might have to do a JSON conversion first. – Katana314 Jun 12 '13 at 19:04
  • @dystroy No big deal about your answer - it made perfect sense to me at first. Then I started reading and found out what `.getItem()` can actually return. I wouldn't have expected that, but then again, it's not a normal property access – Ian Jun 12 '13 at 19:08
  • Where did the answer go? – Russell Jun 12 '13 at 19:14
  • Your code [works just fine](http://jsfiddle.net/MQEDB/2/), so I assume you want to achieve something more, but I'm not sure what it is. I'm not sure what you mean by "accessed through the variable" in "show up to 8 -divs- accessed through the variable". What is "the variable"? Are you referring to `localStorage`, or your `cs` variable? – apsillers Jun 12 '13 at 20:22

1 Answers1

1

localStorage uses string keys, so access them as you do all other keys: Object.keys(localStorage). localStorage is "sandboxed" to a page, so you don't get all keys ever set, only the ones set for the page you're on right now.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153