I have just encountered some very disturbing behavior in jQuery 1.6.2 that I hope someone can explain. Given the following markup...
<div id="test" data-test=" 01">Test</div>
Can someone tell me why accessing the attribute through .data()
causes it to be parsed to an int?
var t = $("#test").data("test");
alert(t); // shows "1"
t = $("#test").attr("data-test");
alert(t); // shows " 01"
Of course I have proof on jsFiddle of this behavior.
The attr() method in jQuery is used to set or return the attributes and values of the selected elements.
jQuery Misc data() Method The data() method attaches data to, or gets data from, selected elements. Tip: To remove data, use the removeData() method.
data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.
We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.
From the doc for data(key)
:
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string.
Since your example string CAN be converted to a number, it is.
Edit: As Joseph points out, this only applies when reading data straight from the element, like you're doing in this example. If you could set it first (i.e. data(key,value)
before reading), then the behavior disappears. The getter, when reading from the actual DOM element, performs type coercion.
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