0

I'm using HTML5's data to store some informations on a div on my website, and whenever I change the value of this data with jQuery, the DOM's updating well, but jQuery doesn't see the update when I try to retrieve the value.

I update the value of this data with $('#myDiv').attr('data-my_data',value);, and get the value back with $('#myDiv').data('data-my_data').

Here's the fiddle to illustrate my problem.

Is this happening because of some jQuery's initial representation of the DOM that doesn't update?

I don't get it, any help will be appreciated!

Configuration : Chrome 25 - jQuery 1.9.0 - Mac OSx 10.7

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Maen
  • 10,603
  • 3
  • 45
  • 71

2 Answers2

1

data-* attributes are mapped to dataset DOMString object, use data method as setter, do not use attr for properties.

$('#testDiv').data('test_data', newData).html("My data is : " + newData);

http://jsfiddle.net/zgKdg/

Ram
  • 143,282
  • 16
  • 168
  • 197
  • Thank you, it works! But why jQuery doesn't see the change of the dataset DOMString object? – Maen Mar 06 '13 at 12:24
  • @Bigood Because `data-*` attribute actually is a property, modifying attributes doesn't change the properties. – Ram Mar 06 '13 at 12:26
  • 2
    @Bigood check http://stackoverflow.com/questions/5874652/prop-vs-attr this for more info – Ravi Gadag Mar 06 '13 at 12:27
1

you can set the values to the data('yourKey','Yourvalue')

$(yourElement).data('isEdit','1');

according to your Example

$('#myDiv').data('data-my_data','value');

Attr : it will add attributges to the dom object.

prop : it will add properites in memory. so your data will be stroed in dataSet of DOM.

for more info check this attr vs prop

Community
  • 1
  • 1
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83