Reputation: 82513
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.
Upvotes: 5
Views: 1935
Reputation: 95065
To add to Paul Equis's answer,
If you want to access it as a string, use the .attr()
method.
var t = $("#test").attr("data-test");
Edit: here's a demonstration showing one of the benefits of jQuery interpreting the data attribute.
Upvotes: 0
Reputation: 6259
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.
Upvotes: 7
Reputation: 11568
jQuery people say:
As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.
Every attempt is made to convert the string (html5 data attribute value) to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method.
From this page: http://api.jquery.com/data/
Upvotes: 0