Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery data(...) not stored in the DOM?

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) :

enter image description here

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>
like image 544
Basj Avatar asked Dec 20 '22 09:12

Basj


2 Answers

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

like image 145
adeneo Avatar answered Dec 30 '22 21:12

adeneo


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.

like image 25
Suchit kumar Avatar answered Dec 30 '22 22:12

Suchit kumar