Jamie
Jamie

Reputation: 371

Dynamically find localstorage key using jQuery

I am trying to work out a way to DRY up the following code, which looks to see if certain local storage keys are present, then does something if they are. It could have many keys, but they will all be numbered to marry to the relevant element id, i.e, key: item1 > #item1 etc.

if (localStorage.getItem('item1')) {
  $('#item1').addClass('active');
}

if (localStorage.getItem('item2')) {
  $('#item2').addClass('active');
}

etc.

I recently learned to do something similar with element id's, so I was wondering if / how I could apply this type of logic to finding local storage key's instead of element id's?

$('*[id^=btn-item]').click(function () {
  var id = $(this).attr('id').slice(-1); 
  $('#item'+id).addClass('active');
}

Upvotes: 1

Views: 1484

Answers (2)

Alnitak
Alnitak

Reputation: 339786

To (correctly) iterate over the possible keys in localStorage without knowing in advance what the maximum possible key number is:

var re = /^item\d+$/;
for (var i = 0, n = localStorage.length; i < n; ++i) {
    var key = localStorage.key(i);
    if (re.test(key)) {
       $('#' + key).addClass('active');
    }
}

Alternatively, reverse the logic and look in the DOM first:

$('[id^="item"]').addClass(function() {
    return localStorage.getItem(this.id) ? "active" : "";
});

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

Note that the slice code only works if your id is smaller than 10.

For greater id I would suggest $(this).attr('id').slice("btn-item".length); which gets 324 from "btm-item324".

This being said, why not just doing this ?

$('*[id^=btn-item]').click(function () {
  var id = $(this).attr('id').slice("btn-item".length); 
  if (localStorage.getItem('item'+id)) {
     $('#item'+id).addClass('active');
  }
}

If you don't want to do this on a button action, you can iterate on the possible keys like this :

for (var i=0; i<100; i++) {
   if (localStorage['item'+i]) $('#item'+i).addClass('active');
}

Upvotes: 1

Related Questions