1

I'm storing an <a> element in localstorage and trying to get it back in a function which runs on window.onload event. Problem is, after storing that element I get [object Object] and when I apply jquery on it, it throws exception. I'm trying to get its parent here. Could anybody help me My code:-

$('a').on('click', function(){
  localStorage.setItem('link', $(this));
})
window.onload=function(){
  var link = localStorage.getItem('link'); //gives [object Object]
  var parent = $(link).parent(); //got error here
}

I'm storing that link so that I could add 'active' class to it and its parent elemnt on page reload/refresh. On load I want them to be active in side menubar. my sidebar menu:-

<ul>
 <li id="1">
  <ul><li><a href="/pages/1"></a></li><li><a href="/pages/2"></a></li></ul>
 </li>
 <li id="1">
  <ul><li><a href="/pages/3"></a></li><li><a href="/pages/4"></a></li></ul>
 </li>
</ul>
niklas
  • 2,887
  • 3
  • 38
  • 70

1 Answers1

0

What you can do is to convert your element to a string before saving to localstorage and converting it back to an object upon retrieval from localstorage.

$('a').on('click', function(){
  localStorage.setItem('link', JSON.stringify(this));

  var retrievedObject = localStorage.getItem('link');

  //do anything with the object from localstorage
  console.log(JSON.parse(retrievedObject));
});

Or you might want another approach. For example, you could store the index of the clicked a-Element in localstorage and reconstruct it on pageload like in the following pen

https://codepen.io/niklasp-the-looper/pen/Xxxyay?editors=1010

$('ul a').each(function(idx, element) {
  $(element).on('click', function() {
    localStorage.setItem('linkIdx', idx);
  });
});

$('#get').on('click', function() {
  var linkIndex = localStorage.getItem('linkIdx');
  var element = $('a')[linkIndex];
  console.log(element);
});

I hope you get the idea. It is not wise to store more than you really need. Besides storing jQuery objects with functions is not possible as mentioned below.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
niklas
  • 2,887
  • 3
  • 38
  • 70