I'm trying a very simple task working with data-attr and jQuery, check this example:
Markup:
<div data-name="Testing"></div>
JS
$(function(){
var div = $('div');
$(div).append($(div).data('name'));
$(div).attr('data-name', ' - Testing 2');
$(div).append($(div).data('name'));
console.log(div);
});
You can test it here: http://jsfiddle.net/YsKJJ/16/
So, it should appends inside the div
the text Testing - Testing 2
, but prints TestingTesting
. In console I checked if the attr was changed in the object, and yes, has the new value - Testing 2
but jQuery still returns the original value :(
Any idea?
UPDATE:
So, the reason of this behavior according jQuery docs:
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
More information: jQuery Data vs Attr?