Independent from the HTML id attribute, is there a good way to define a unique element identifier in JavaScript to use with HTML5 local storage?
localStorage.setItem('uniqueid', value);
Could do this:
var uid = ancestor.index(element); // uid = 0
localStorage.setItem(namespace + uid, value);
The problem is that if the element order changes, the data is not associated with the right element:
var uid = ancestor.index(element); // another element is prepended, so uid = 1
localStorage.getItem(namespace + uid);
EDIT – real example
HTML code:
<ul>
<li aria-hidden="true">foo</li>
<li>bar</li>
</ul>
jQuery code:
var ul = $('ul');
ul.find('li').each(function() {
var element = $(this),
uid = ul.index(element),
data = JSON.parse(this.storage.getItem(uid));
// load
console.log(data.hidden);
// save
this.$window.bind('unload', function() {
localStorage.setItem(uid, JSON.stringify({
hidden: typeof element.attr('aria-hidden') === 'string',
}));
});
});
Now I am using the index of each list item to create a unique identifier. I could set a data-uid with HTML like so:
<li data-uid="foo">foo</li>
Is there a way to set the unique identifier dynamically?
If the data being stored depends on the specific order of elements, that seems to suggest it will not be helpful to persist this data beyond the current page. You may wish to look at
data-*attributes such as jQuery implements in$.data.This will allow you to store arbitrary data associated with any element.