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?
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.
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.
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).
The HTML data value attribute is used to Specify the machine-readable translation of the content of the element.
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()
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With