2

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?

Community
  • 1
  • 1
nikoskip
  • 1,860
  • 1
  • 21
  • 38
  • 2
    `$(div).data('name', ' - Testing 2');` - also, don't use data attributes unless you have a very good reason. – Benjamin Gruenbaum Dec 06 '13 at 22:57
  • That is the way data api works. You need to set it with data-api itself. – PSL Dec 06 '13 at 22:58
  • @SalmanA yes, I just realized of that. – nikoskip Dec 06 '13 at 23:04
  • 1
    Just remember this: element data values are *in memory* and are only initially, if needed, pulled from the value of the corresponding data-attribute. Attributes, on the other hand, are always reflected *in the DOM*. – user2864740 Dec 07 '13 at 00:37

2 Answers2

2

You are changing the attribute but this doesn't automatically update the data. This works:

$(function(){
    var div = $('div');
    div.append(div.data('name'));
    div.data('name', ' -  Testing 2');
    div.append(div.data('name'));
});
mayabelle
  • 9,804
  • 9
  • 36
  • 59
1

Working demo http://jsfiddle.net/DDv8U/

rest should fit the need :)

code

$(function(){
    var div = $('div');
    $(div).append($(div).data('name'));
    $(div).data('name', ' -  Testing 2');
    $(div).append($(div).data('name'));
});
Tats_innit
  • 33,991
  • 10
  • 71
  • 77