Why does jQuery automatically parse my data- * attributes?

I just noticed that if I try to read the html5 data-* attribute using .data , it will parse automatically, while reading the value with .attr will not.

 data-id="00123456" 

Why is this the default behavior? I have certain objects whose fields have numerical values ​​inside a string, for example. "00123456", not 123456.

I missed a jQuery changelog note or what?

+4
source share
1 answer

Quote from the documentation :

Like jQuery 1.4.3, the HTML data attributes will be automatically drawn into the jQuery data object. Attribute handling using inline dashes has been modified in jQuery 1.6 to meet the W3C HTML5 specification.

For example, given the following HTML:

<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

All of the following jQuery codes will work.

$("div").data("role") === "page";

$("div").data("lastValue") === 43;

$("div").data("hidden") === true;

$("div").data("options").name === "John";

Each attempt is made to convert a string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null); otherwise, it remains as a string. To get the value attribute as a string without any attempt to convert it, use the attr () method.

So it seems that after jQuery 1.6, the .data method parses the values.

+7
source

All Articles