jQuery's .data() does a couple things but it doesn't add the data to the DOM as an attribute. When using it to grab a data attribute, the first thing it does is create a jQuery data object and sets the object's value to the data attribute. After that, it's essentially decoupled from the data attribute.
Example:
<div data-foo="bar"></div>
If you grabbed the value of the attribute using .data('foo')
, it would return "bar" as you would expect. If you then change the attribute using .attr('data-foo', 'blah')
and then later use .data('foo')
to grab the value, it would return "bar" even though the DOM says data-foo="blah"
. If you use .data()
to set the value, it'll change the value in the jQuery object but not in the DOM.
Basically, .data()
is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. .attr()
is for setting or checking the DOM element's attribute value and will not touch the jQuery data value. If you need them both to change you should use both .data()
and .attr()
. Otherwise, stick with one or the other.
.data()
unless you actually have a reason to use.attr()
. – Chopping