Search code examples
javascriptclonesession-storage

JS sessionStorage to store HTML node and then re-use it later


I need to clone some HTML content, store it in sessionStorage, to then re-deploy the stored HTML back into the DOM on another page. For the moment with my testing I'm just doing it all on one page and summoning the sessionStorage with a page refresh.

So, here is what I have come up with so far.

var exp561CardFour = document.getElementById('dashboard_item_four');
var clnCardFour = exp561CardFour.cloneNode(true);
sessionStorage.setItem('storedCardFour', clnCardFour);

When I go to grab the HTML with this bit of code in the console...

var grabCardFour = sessionStorage.getItem('storedCardFour');

...I end up with this:

enter image description here

Please help :)

edit: FYI clnCardFour just contains some HTML and it works ok

enter image description here

edit with Parking Masters suggestion in the console:

enter image description here


Solution

  • The Storage API (sessionStorage/localStorage) only stores strings. When you call:

    sessionStorage.setItem('storedCardFour', clnCardFour);

    the API uses the .toString() method against the object clnCardFour - which returns [object HTMLLIElement].

    So you need the string representation of that Node. You can achieve that by getting the OuterHTML of the Node like this:

    sessionStorage.setItem('storedCardFour', clnCardFour.outerHTML);

    When you need to restore that Node, simply use the parent Node's .innerHTML property to place it back into the DOM.

    let div = document.querySelector('div');
    let exp561CardFour = document.getElementById('dashboard_item_four');
    sessionStorage.setItem('storedCardFour', exp561CardFour.outerHTML);
    let clonedFromStorage = sessionStorage.getItem('storedCardFour');
    div.innerHTML += clonedFromStorage
    
    <div>
      <i id="dashboard_item_four">Hello there!</i>
    </div>
    

    And here is a JS Bin Example