Mirror318 Mirror318 - 1 year ago 189
jQuery Question

jQuery $(this).data() is returning old values

I have the following code:

updateColors = function() {
$(".color-preview").each(function() {
return $(this).css('background-color', $(this).data('color'));
return null;

I put a breakpoint on the 3rd line, and type the following into the console:

> this
<div class=​"color-preview" data-observer=​"{"attr":​"data-color", "observe":​"btn_col"}​" data-color=​"#ffff00" style=​"background-color:​ rgb(153, 0, 255)​;​">​</div>​

> $(this).data('color')

As you can see, the actual element's
. However, jQuery's
method is returning
, which was the value of the element's
, but has been changed (and using the breakpoint, I can see that yes it has already changed).

Answer Source

jQuery only reads-through to data attributes with .data - that is, the data attribute will only be inspected the first time it is accessed (and never if the first access is an assignment).

Internally, jQuery it maintains it's own 'data cache' which otherwise has no relation to data attributes. This internal cache is primed through from the DOM data attributes on the first access of a given key.

If the goal is to always read and/or mutate the DOM attributes, use the .attr method instead.

The relevant parts from https://github.com/jquery/jquery/blob/master/src/data.js are shown below.

// Attempt to get data from the cache
// The key will always be camelCased in Data
data = dataUser.get( elem, key );
if ( data !== undefined ) {
   return data;

// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, key );

// ..

function dataAttr( elem, key, data ) {
    var name;

    // If nothing was found internally, try to fetch any
    // data from the HTML5 data-* attribute
    if ( data === undefined && elem.nodeType === 1 ) {
        // ..

        // Make sure we set the data so it isn't changed later
        // (NOTE: This is the side-effect that primes the cache
        //  entry and prevents reading the updated data attribute value.)
        dataUser.set( elem, key, data );

See also:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download