I'm developing code using jQuery and need to store data associated with certain DOM elements. There are a bunch of other questions about how to store arbitrary data with an html element, but I'm more interested in why I would pick one option over the other.
Say, for the sake of extremely simplified argument, that I want to store a "lineNumber" property with each row in a table that is "interesting".
Option 1 would be to just set an expando property on each DOM element (I hope I'm using the term 'expando' correctly):
$('.interesting-line').each(function(i) { this.lineNumber = i; });
Option 2 would be to use jQuery's data() function to associate a property with the element:
$('.interesting-line').each(function(i) { $(this).data('lineNumber', i); });
Ignoring any other shortcomings of my sample code, are there strong reasons why you would choose one means of storing properties over the other?
If you are authoring a plugin you should use $.data
. If you need to store the attribute often and rarely need to query the DOM for it then use $.data
.
Update 5 years later: jQuery does not query the DOM based on expando properties set, and hasn't done so for a while. So use $.data
. There's no reason to pollute the DOM when there is no pragmatic use to do so.