If data-x
is in the DOM like this :
<div id="blah" data-x="143">Hello</div>
and I modify it with
$('#blah').data('x', 13687)
then it seems that the data-x
is not modified in the DOM (use browser's Inspect feature on the snippet code below) :
Is this the normal behaviour?
Example:
console.log($('#blah').data('x'));
$('#blah').data('x', 13687)
console.log($('#blah').data('x'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="blah" data-x="143">Hello</div>
jQuery's data()
method does not set data attributes, it stores the data in an internal object.
HTML5 data attributes will be automatically pulled in to jQuery's data object, which means the initial value of the data object reflects whatever is given in the attribute, but changing the value with data()
will not update the attribute, only the internal data object that jQuery uses.
So yes, it's normal that the attribute doesn't change, and it's supposed to be like that.
If for some reason you have to change the actual attribute, you can use attr()
$('#blah').attr('data-x', 13687)
Note that this is generally not needed if you consistently use data()
in your code, and you're not using other scripts that rely on the data attribute.
You'll find more about how attributes are handled, and how jQuery stores the data, in the docs
you should be using $('#blah').attr('data-x', 13687)
not $('#blah').data('x', 13687)
,because data()
is not the method to get the attribute data-x to set you have use attr()
to set the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With