Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?

Tags:

html

jquery

Here's a simple example to illustrate the behavior:

Given this html markup:

<div data-company="Microsoft"></div> 

and this jQuery code (using jQuery 1.5.1):

// read the data alert($("div").data("company")); // returns Microsoft <<< OK!  // set the data $("div").data("company","Apple"); alert($("div").data("company")); // returns Apple <<< OK!  // attribute selector alert($("div[data-company='Apple']").length); // returns 0  <<< WHY???  // attribute selector again alert($("div[data-company='Microsoft']").length); // returns 1  <<< WHY???  // set the attribute directly $("div").attr("data-company","Apple"); alert($("div[data-company='Apple']").length); // now returns 1 <<< OK! 

Since jQuery automatically imports the HTML5 data-* into jQuery's data object, shouldn't the attributes be updated as well when the data changes?

like image 805
James H Avatar asked Mar 31 '11 23:03

James H


People also ask

What is data-* attribute?

The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.

What is the use of data in HTML?

Definition and Usage The <data> tag is used to add a machine-readable translation of a given content. This element provides both a machine-readable value for data processors, and a human-readable value for rendering in a browser.

What is data section in HTML?

Definition and UsageThe data-* attributes gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

What is data value in HTML?

The HTML data value attribute is used to Specify the machine-readable translation of the content of the element.


Video Answer


2 Answers

Normally, there's not a need for roundtripping .data()'s if you're consistent in using .data() to access/set/modify data on DOM elements. For that reason, it makes sense to avoid the performance overhead of accessing the DOM for every .data() set/modify operation (.data() stores its values in jQuery.cache internally).

If you want to force the roundtrip behavior yourself, you could subscribe to the "setData" or "changeData" events and then push the .data() update in those events through to the corresponding DOM element via .attr().

like image 162
Dave Ward Avatar answered Oct 11 '22 20:10

Dave Ward


This is the correct behavior according to the docs:

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

(from: http://api.jquery.com/data)

like image 30
Craig Avatar answered Oct 11 '22 22:10

Craig