Will the jQuery $("..").data("key", value) method set the data-key attribute if one is present?
Adam Freeman’s Pro jQuery states that it does:
Tip The data method takes the data attributes into account when
setting values as well. When you specify a key, such a [sic] product, the
data method checks to see whether there is a corresponding HTML5 data
attribute, such as data-product. If there is, then the value you
specified is assigned to the attribute. If not, then the data is
stored internally by jQuery.
But I thought that it didn’t, and the test that I ran implies that it doesn’t. (I checked the errata section—nothing)
Full code is below, but the short of it is that when I set the data-name attribute by calling the attr method, the attribute value changes and can be seen in the chrome elements tab, and retrieved into newValue. When I set it with the data method, neither of these conditions are satisfied; it seems as though using data() always sets the value internally and never on the attribute, even if one is present.
Unfortunately, the docs’ only mention of html5 data-attributes is in the section of the data method that takes only a key, and returns the concomitant value; the description of data("key", value) doesn’t seem to mention html5 data-attributes at all.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.js"></script>
<script type="text/javascript">
$(function () {
var oldValue = $("#d").data("name");
alert("old value " + oldValue);
$("#d").data("name", "Adam");
//$("#d").attr("data-name", "Adam");
var newValue = $("#d").attr("data-name");
alert("new value " + newValue);
});
</script>
</head>
<body>
<div id="d" data-name="none"></div>
</body>
</html>
According to jQuery’s .data() method documentation: