One of the problems with HTML is that there is no attribute to store additional data for an element. Usually this is solved by storing the data in the elements id, as a class or as a hidden child element. There is a much better way to do this with jQuery's data method.
Here is a simple example of how to use it.
$('#MyElement').data('customerId', '12345');
Here is an example of how we could use it to keep track of whether an article element is expanded or not.
<div class="article">
<h2>Lorem ipsum</h2>
<p >Lorem ipsum ei eam esse molestiae maiestatis, eum te zzril congue. Mei ex autem persius, pro facer aperiri ornatus ad.</p >
</div>
$(document).ready(function() {
$('.article p').hide(); // Hide the body text of all article elements by default
$('.article').click(function() {
var article = $(this).parent(); // Select the clicked article
var body = article.find('p'); // Select the body text of the article
// Check if the article is expanded or not (if the body text is visible or not)
if (article.data('expanded')) {
article.data('expanded', false); // Set this article to expanded: false
body.slideUp(); // Hide the body text
}
else {
article.data('expanded', true); // Set this article to expanded: true
body.slideDown(); // Show the body text
}
});
});
You can also use objects as value like this.
$('#MyElement').data('position', { 'x' : 33, 'y' : 42 } );
alert('The x value of MyElement is ' + $('#MyElement').data('position').x);