Last Updated: February 25, 2016
·
2.054K
· dmtrs

jquery.data() does not manipulate the dom

or Why you should not (be careful) use data attribute in selectors.

While I was working with the $().data()</code> function of the jquery library, me and my colleague @smas realized that data is not actually manipulating the DOM but stores the changes in the $.cache</code>. That actually can stop you from using data attribute in a selector, because you wont get the proper results.

For example, oen your browsers console and address the following code:

$('body').append("<div id='test' data-id='15' ></div");
$('#test').data('id'); //Returns 15
$('#test').data('id', 20); 
$('#test').data('id'); //Returns 20
//Now if you try to use data as selector
$('div[data-id=20]'); //Nothing will be returned
$('div[data-id=15]'); // Will get you the "proper" element

$('div[data-id=15]').data('id'); //Will return 20 :)

This acutally can be found in the jquery 1.6.3 release changelog ( under Better handling of HTML5 data attribute names ).

Remember, however, that the $().data() API only reads the HTML5 data- attributes initially, and does not keep subsequent data changes in sync with attributes for performance reasons. To update the actual attributes in the HTML markup, use .attr().

2 Responses
Add your response

Thanks for the helpful clarification!

over 1 year ago ·
over 1 year ago ·