Reputation: 6746
The idea is pretty simple, yet I cannot figure it out. Basically I want to save an element that was clicked in the sessionStorage. However, this is not easy because sessionStorage only takes strings.
I am attatching a click event to all my navigation buttons. (This does not work of course)
navButtons.addEventListener("click", function () {
sessionStorage['active-nav'] = $(this);
});
How would I save a DOM element and access it later?
EDIT
Basically when the page is reloaded, I want to keep track which element was clicked before and the apply some CSS to it once the new page is loaded. For example changing the background color of that element to orange, etc.
Therefore, I need to somehow save some information about that element in the sessionStorage and access the element/ find the element, once the page is reloaded. I used the approach of adding an Id to all elements and then using the javascript function document.getElementById("test")
, to find it. However, there are quite a few navigation elements, so adding Ids to all of them would probably not be the cleanest solution. What would be the best way of solving this wihtout adding Ids to everything?
Upvotes: 1
Views: 2598
Reputation: 22949
I'd say you should either:
Store it's id
, then use document.querySelector()
to reselect it using the stored id.
Produce & store a reverse selector, by using a library such as SimmerJS, then use document.querySelector()
to reselect it using the stored selector.
Reverse selectors avoid the need to add explicit ids to all relevant elements.
Here's how reverse selectors work:
window.simmer = window.Simmer.configure({ depth: 10 })
document
.querySelector('.container')
.addEventListener('click', e => {
console.log(simmer(e.target))
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/simmer.js"></script>
<div class="container">
<div class="left">
<button> Click Me </button>
</div>
<div class="right">
<button> Click Me </button>
</div>
</div>
Then save the produced selector and use it again to reselect the element on page load. No explicit ids needed.
Saving selectors avoids serialising & rehydrating HTML, so you don't loose any event listeners attached to the element, plus they won't take up a lot of storage space in case you plan to do this for a lot of elements.
Upvotes: 2
Reputation: 12152
navButtons.addEventListener("click", function () {
sessionStorage.setItem('div', this.outerHTML);
});
Save using the outerHTML
property of the element
To get the same element
var element=sessionStorage.getItem('div');
Upvotes: 1
Reputation: 1
You can set the sessionStorage
value to .outerHTML
of the element.
sessionStorage['active-nav'] = this.outerHTML;
If more data than only the HTML is needed you can store a JSON
string at sessionStorage
, where one of the values is the .outerHTML
.
Upvotes: 1