Skip to content Skip to sidebar Skip to footer

Jquery Data(...) Not Stored In The Dom?

If data-x is in the DOM like this :
Hello
and I modify it with $('#blah').data('x', 13687) then it seems that the data-x is not mod

Solution 1:

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

Solution 2:

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.

Solution 3:

console.log($('#blah').attr('data-x'));
$('#blah').attr('data-x', 13687);
console.log($('#blah').attr('data-x'));

Use the attr() function to handle the attributes and their data.

UPDATE: I write small plugin for you!

$.fn.dataRead=function(a,b){
    this.attr("data-"+a,b);
};

Now work how you need: example:

console.log($('#blah').dataRead('x'));
    $('#blah').dataRead('x', 13687);
    console.log($('#blah').dataRead('x'));

Post a Comment for "Jquery Data(...) Not Stored In The Dom?"