Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 data attribute access using jquery [duplicate]

Tags:

html

jquery

Which is the difference between code bellow?

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

and,

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

or both are same?

like image 884
Tauhidul Islam Avatar asked Jun 18 '26 09:06

Tauhidul Islam


1 Answers

If look at these 2 function from point of working with data-* attributes, them is pretty equal. You can consider data() function as shortcut for attr() function in this case.

But with data() function you can do some more complex things. You can save not only simple strings or some text which usually attached as html attribute, but you can save some custom object. For example you can save 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");
like image 96
m1burn Avatar answered Jun 20 '26 01:06

m1burn