Reputation: 1479
Can anyone explain the weird jquery behaviour found in the following fiddle?
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.
Upvotes: 1
Views: 493
Reputation: 95065
.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
Upvotes: 7