Alvaro
Alvaro

Reputation: 41605

Data attribute changes not detected with jQuery

I am changing the data-demo attribute of a div element and when I want to check it with in another event, it always shows me the initial value of it instead of the current value.

This is the code I am using:

$('#showValue').click(function(){
    alert($('.value').data('demo'));
});

$('.update').click(function(){
   $('.value').text('updated').attr('data-demo', 'updated');
});

Why is this happening?

Here's a fiddle with the example I am talking about: http://jsfiddle.net/f5Cpm/

Thanks.

Upvotes: 5

Views: 2091

Answers (2)

David Mulder
David Mulder

Reputation: 26990

The jQuery .data() functions aren't truly supporting the HTML5 dataset functionality, but rather load in all the html5 dataset data into their own data collection. In consequence updates to the dataset by changing the attribute are not reflected in the jQuery internal data collection.

In other words, you either need to consequently use dataset.demo, $().data("demo") or $().attr("data-demo"). The advantage of the second being that it cross browser of course and part of jQuery if you're using jquery for the rest of the application.

Upvotes: 6

uross
uross

Reputation: 431

After the internal data is first initialized, it never goes back to the attribute to get or set the value, therefore updating the attribute will not update what is stored in .data() if you've already used .data on that element.

Read more here

Upvotes: 9

Related Questions