Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 data-* attribute type casting strings and numbers

Why is the value of data-value="2.0" cast to a String and the value of data-value="2.5" cast to a Number? I can handle this fine within my function. I'm just trying to understand a little more about how Javascript handles Numbers and Strings. This kind of caught me off guard.

<a data-value="2.0">2.0</a> <a data-value="2.5">2.5</a> 
$("a").click(function() {     alert(typeof $(this).data( "value"));    }); 

[ Fiddle With It ]

like image 383
Matt Avatar asked Sep 30 '14 16:09

Matt


People also ask

Can data -* attribute contain HTML tags?

The data-* attribute is a Global Attribute, and can be used on any HTML element.

What are custom attributes in HTML5?

Custom attributes are attributes that are not part of the standard HTML5 attributes but are explicitly created. They allow us to add our own information to HTML tags. These are not specific and can be used with all the HTML elements.

What is data value attribute in HTML?

The HTML data value attribute is used to Specify the machine-readable translation of the content of the element.

What is the recommended way to add custom HTML5 attributes?

You can use getAttribute() and setAttribute() in JavaScript to get and set the value of different data attributes. The getAttribute method will either return null or an empty string if the given attribute does not exist. Here is an example of using these methods: var restaurant = document.


1 Answers

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

[...document.querySelectorAll("a")].forEach(a =>      console.log("type: %s, value: %o",                   typeof a.dataset.value,                   a.dataset.value)  );
<a data-value="2.0">2.0</a>  <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

like image 101
canon Avatar answered Sep 23 '22 04:09

canon