1

Can anyone explain the weird jquery behaviour found in the following fiddle?

http://jsfiddle.net/HSyS6/2/

I have the following html...

<div id="test" data-prevy="0"></div>

With the following jquery...

console.log($('#test').data('prevy'));
console.log($('#test').attr('data-prevy'));

$('#test').attr('data-prevy', 2);

console.log($('#test').data('prevy'));
console.log($('#test').attr('data-prevy'));

$('#test').attr('data-prevy', 1);

console.log($('#test').data('prevy'));
console.log($('#test').attr('data-prevy'));

Which outputs...

0
0
0
2
0
1

When I would expect it to output...

0
0
2
2
1
1

I realize that if you set the value via .data (IE: .data('prevy', 2);) that the value will not reflect in the DOM, but I am doing the opposite and getting even more unexpected results.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
lionpants
  • 1,469
  • 14
  • 24

1 Answers1

7

.data() does not set or change the attribute of the element, it just gets the value of it initially, then updates an internal object stored within jQuery for the element.

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.

Since you are only updating the attribute, the internal stored data is never updated, only the attribute. This is the intended behavior.

For reference, https://github.com/jquery/jquery/blob/1.9-stable/src/data.js

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • I'm not expecting it to change the attribute, I'm expecting it to get the new value for the attribute which I updated via `.attr()`. – lionpants Apr 30 '13 at 20:43
  • 1
    It looks like it is successfully getting the new attribute value--the "failed" calls are the ones using `.data`. – Andrew Whitaker Apr 30 '13 at 20:44
  • 1
    It doesn't and isn't supposed to, as i have explained. I split it into two sections to bring more emphasis to it. – Kevin B Apr 30 '13 at 20:45
  • 1
    @KevinB is right. If you're wanting to update the data, why don't you use the `.data( key, value )` format? This will update the object data used by jQuery to retrieve the value. – Axel Apr 30 '13 at 21:15
  • Makes sense now, thanks guys. I guess they're not really meant to be combined then. I needed to keep the attribute updated due to some server side stuff. Anyway, I'll just stick with setting and reading from `.attr()` then. Thanks! – lionpants May 01 '13 at 12:04