Question

When I use jQuery.data to change the value the attribute in the DOM doesn't change. But I like when the attribute in the DOM changes, its much easier to debug stuff.

So is it ok to use $().attr("data-value") to change data-attributes?

Just a little fiddle to show that mixing $().attr and $().data won't work well together:

http://jsfiddle.net/AvRJc/

Was it helpful?

Solution

The data function manages a cache of data for an element that jQuery provides, not data-* attributes. The only interconnection between the data function and data-* attributes is that data will initialize its cache of information from data-* attributes if you request a key that matches a data-* attribute.

Using data to set data will never update a data-* attribute.

It's fine to use attr to update the attribute, you just need to be consistent: Either use the attribute (via attr) for both getting and setting, or use data for both getting and setting, as they manage different things.

Using attr means you're really updating the attribute on the element, which means you can use the values you set in selectors and such (both CSS and jQuery), but also means you are limited to getting and setting only string values.

Using data means you're only updating the data cache, not the element, which means you can't use those values in selectors and such (because they're not stored anywhere in the DOM), but means you can get and set the full range of JavaScript data types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top