Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is jQuery.data() modifying the HTML5 data-x attribute value?

Tags:

jquery

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.

like image 685
Josh Stodola Avatar asked Sep 30 '11 17:09

Josh Stodola


People also ask

How set value to data attribute in jQuery?

The attr() method in jQuery is used to set or return the attributes and values of the selected elements.

What is the use of the jQuery data method?

jQuery Misc data() Method The data() method attaches data to, or gets data from, selected elements. Tip: To remove data, use the removeData() method.

Why is the data attribute used in HTML?

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.

How do you get the value of data attribute in JS?

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.


1 Answers

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.

like image 124
Paul Phillips Avatar answered Sep 28 '22 15:09

Paul Phillips