Accessing HTML5 data attributes using jquery

What's the difference between the code below?

$("demo").data("title");

      

and

$("demo").attr("data-title");

      

or are both the same?

+3


source to share


1 answer


If you look at these 2 functions from the point of dealing with data- * attributes, they are pretty equal. You can think of the data () function as a shortcut to the attr () function in this case.

But with the data () function, you can do more complex things. You can save not only simple strings or text that is usually attached as an html attribute, but you can save some kind of custom object. For example, you can store some object with data like this:



// Attaching custom object to DOM element
var someObj = { id: 1, name: "whatever" };
$("demo").data("someObj", someObj);

// Receiving previously attached object from DOM element
var someObjFromData = $("demo").data("someObj");

      

+2


source







All Articles