Yuanhai Shi

Learn and Share

A web developer from New Jersey, US.


只有经历地狱般的折磨才有攀登天堂的力量。

jQuery - data() vs attr()

$.data() and $.attr() are very common functions we use daily. HTML5 introduces data-* attributes on DOM elemnts to store extra information.

####Data attributes defined inline on DOM element.

<div id="div1" data-name="Bill"></div>
$("#div1").data("name");		//"Bill"
$("#div1").attr("data-name");	//"Bill"

As you seen above, both data() and attr() can set and get the name on div1.

####Data attributes defined using JS.

<div id="div1"></div>
$("#div1").data("name", "Bill");
$("#div1").data("name");		//"Bill"
$("#div1").attr("data-name", "Bob");
$("#div1").data("name");		//"Bill"
$("#div1").attr("data-name");	//"Bob"

If you use data() to set data-* attribute on node, the actual value won’t be changed later by using attr().