Skip to content Skip to sidebar Skip to footer

What Is The Advantage Of Using 'data-attribute' Over $.data In Jquery?

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 foo! //Set attr da

Solution 1:

They serve different purposes. Yes, it seems like they can be used to achieve the same thing, but under the hood there are differences.

  1. While you can save simple values in attributes, you can not save DOM nodes, because you will creatememory leaks. Neither can you save objects, arrays, functions, etc...

  2. $.attr() might be faster than $('selector').data(), but it is not faster than the low-level method jQuery.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 the data- 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().

Solution 2:

I'm not a guru, that' s for sure... but it appears to me that two obvious differences are the time/environment when the 'data' is set, and the structure(type) of data that will be stored/accessed.

Concider this scenario:

<a id="foo" data-me="some string data" href="#">foo!</a

This pice of html was maybe generated on the server side. If so,only the server side needs to know about the 'data-me' value origin. One limitation is that the attribute must be a string , or a string representation of an object (JSON)

var customData = 
{
    date:newDate(),
    otherProp:'some value',
    someFunc: function(a,b)
    {
        // function dody
    }
};
$('#foo').attr('data-me', customData)

From the javascript(medium), at a certain moment, triggered by a certain event(time), you can use jQuery to bind a dom element to a given object (not necessarily a string)

So the latter way ($('#foo').attr('data-me', customData)), removes the 'only string' limitation and allows you to bind to a dom element any kind of js object , even functions.

Post a Comment for "What Is The Advantage Of Using 'data-attribute' Over $.data In Jquery?"