I was wondering what the advantage is of using data assignment to the DOM vs. NOT to the DOM
i.e. Assume we have said HTML
<a id="foo" href="#">foo!</a>
//Set attr data-me so it's <a id="foo" data-me="yay" href="#">foo!</a>
$('#foo').attr('data-me', 'yay');
//Retrieve the data 'yay'
$('#foo').data('data-me');
Over and above direct assignment:
var myInput = $('#foo');
//Add some data
$.data(myInput, 'data-me', 'yay');
//Retrieve the data 'yay'
$.data(myInput, 'data-me');
My understanding is that the later is MUCH faster and therefore I can’t see the sense in adding data-someAttr all over the DOM when it’s not required ?
They serve different purposes. Yes, it seems like they can be used to achieve the same thing, but under the hood there are differences.
While you can save simple values in attributes, you can not save DOM nodes, because you will create memory leaks. Neither can you save objects, arrays, functions, etc…
$.attr()might be faster than$('selector').data(), but it is not faster than the low-level methodjQuery.data(). The first data method has much more overhead than the second, however the second one does not carry all the functionality of the first one. For example, it does not get the data out of thedata-attributes.Thus, I think it’s best to use
data-attributes at load time, so you can extract the data with$('selector').attr(), and handle the application state with$.data().