Search code examples
javascripthtmljquerycustom-data-attribute

Why does jQuery remove brackets from a custom data attribute?


I am trying to get the content of a data attribute with jQuery, but returned data is not what I had set.

With this simple example:

<div id="test" data-test="[1]"></div>

But $('#test').data('test') returns 1 instead of [1]

No problem using pure JavaScript.

View it online: https://jsfiddle.net/jojhm2nd/


Solution

  • jQuery's data is not an attribute accessor function. (This is a common mistake, easily made.) To just access the attribute, use attr.

    $("#test").attr("data-test");
    

    data does read data-* attributes, but only to initialize jQuery's data cache for that element. (And it never writes attributes.) It does a whole series of things including changing names (data-testing-one-two-three becomes testingOneTwoThree, for instance) and interpreting the values. In this case, it interprets the value as an array because it starts with [. When you show that array with alert, it's coerced to a string, and when you coerce an array to a string, that does an Array#join. If your attribute had been [1, 2], for instance, you'd've seen 1,2 as the result.

    From the docs linked above:

    Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.

    When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.