12

I have this HTML:

<input type="text" id="query" data-source="whatever">

I have some jQuery that changes the data attribute successfully i.e. "whatever" changes to "test"

$(function() {
    $('#query').data('source', 'test');
    console.log($('#query').data());
});

but if I inspect the page using Chrome, the data attribute has not been updated in the element.. I can print it in console, but I can't inspect the new value! Very confusion. Any ideas?

here is the fiddle

1

5 Answers 5

13

The data isn't stored on the element (use attr or prop for that). Instead jQuery maintains it in $.cache.

Sign up to request clarification or add additional context in comments.

1 Comment

$('#query').data() gives the map of all the data attributes stored with the element take a look here jsfiddle.net/r5YV9/10. You don't have to use prop or attr to access them.
1

If you're doing anything crazy like using the data attribute to apply style (no, it's not really crazy) then you need both jQuery's cache and the DOM to update.

Swap out the jQuery

$element.data(key, value);

which won't update the DOM to a method that does both

var data = function($element, key, value) {
    $element.data(key, value);
    $element.attr('data-'+key, value);
}

data($element, key, value);

Note: I always put $ in front of jQuery variables, in case anyone is confused about that. ;)

Comments

0

In your fiddle you have this code.

$(function() {
    $('#query') = $('#query').data('source', 'test');
    console.log($('#query').data());
});

which has error ("Invalid left-hand side in assignment"), because $('#query') is a function call and you are assinging the response of .data('source', 'test') to it.

Change it to

$(function() {
    $('#query').data('source', 'test');
    console.log($('#query').data());
});

it will work fine.

Take a look http://jsfiddle.net/r5YV9/10/

Comments

0

Refer to Jquery Documentation about data() please and you'll see there:

Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr.

So, you should use

$('#query').attr('data-source', 'test');

Comments

0

The jQuery data() stores the information in locally defined function data. Whereas jQuery attr() stores the information directly on the element in attributes that are publicly visible upon inspection.

So when you use jQuery data(), the data is not accessible from outside of jQuery directly and it will not be visible upon inspection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.