jQuery .data() does not work, but .attr() does

I ran into a similar “bug” a few days ago when working with .data() and .attr('data-name') for HTML5 data attributes.

The behavior you’re describing is not a bug, but is by design.

The .data() call is special – not only does it retrieve HTML5 data attributes it also attempts to evaluate/parse the attributes. So with an attribute like data-myjson='{"hello":"world"}' when retrieved via .data() will return an Object while retrieval via .attr() will return a string. See jsfiddle example.

Since .data() does extra processing jQuery stores the results of attribute evaluation in $.cache – after all, once a data attribute has been evaluated it would be wasteful to re-evaluate on every .data() call – especially since data variables can contain complex JSON strings.

I said all that to say the following: After retrieving an attribute via .data() any changes made by .attr('data-myvar', '') will not be seen by subsequent .data() calls. Test this out on jsfiddle.

To avoid this problem don’t intermix .data and .attr() calls. Use one or the other.

Leave a Comment