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');
}
To (correctly) iterate over the possible keys in
localStoragewithout knowing in advance what the maximum possible key number is:Alternatively, reverse the logic and look in the DOM first: