HTML5 data-* attribute type casting strings and numbers

Those values are simply strings to vanilla javascript; it’s not attempting any conversion on its own.

console.table(
  [...document.querySelectorAll("a")]
    .map(({dataset:{value}}) => ({
      type: typeof value,
      value
    }))
);
<a data-value="2.0">2.0</a>                                                       <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script><script>console.config({maximize:true,timeStamps:false})</script><style>.as-console-wrapper{display:block;}</style>
<a data-value="2.5">2.5</a>

jQuery, on the other hand, tries to determine and convert to the appropriate type when accessing data attributes via data(). It’s (arguably) an issue with their implementation. Their documentation (emphasis mine) actually addresses this:

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.

See also HTMLElement.dataset

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)