Using jQuery 1.7.2, how do I update the data-* attrs in my elements when the data model is updated?
For example:
$('el').attr('data-x', 400);
var data = $('el').data( );
data.x += 100;
Changing the $(el).data() does not seem to push the changes back to the elements’ data-* attrs.
Why would I want this? I would like to use the built in jQuery selectors with up-to-date data .
There’s no reason to push data back onto the element’s attribute unless you’re going to be working directly with the attribute values (such as in a non-jQuery plugin). The changes only happen client-side, so it’s much more performant to simply cache the values retrieved from the
[data-*]attributes.If you absolutely must update the attribute value, you should use the
.attr()method.Additionally, when retrieving data, it’s important to know that the
.data()method will try to figure out what sort of data type your content is: