Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
HTML5 data-* attribute type casting strings and numbers
HTML5 data-* attributes are always stored as strings, regardless of whether they contain numeric values. To properly work with these values, you need to understand type casting and conversion methods.
Understanding data-* Attribute Type Casting
When you retrieve values from data attributes using the dataset property, they are always returned as strings. For numeric operations, you'll need to convert them explicitly.
Example
For data-attribute type casting of Numbers and Strings, use the following approach ?
<!DOCTYPE html>
<html>
<head>
<title>Data Attribute Type Casting</title>
</head>
<body>
<a data-value="6.0">6.0</a>
<a data-value="6.5">6.5</a>
<a data-value="hello">hello</a>
<script>
[...document.querySelectorAll("a")].forEach(a =>
console.log("type: %s, value: %o", typeof a.dataset.value, a.dataset.value)
);
</script>
</body>
</html>
The output of the above code is ?
type: string, value: 6.0 type: string, value: 6.5 type: string, value: hello
Converting to Numbers
To convert data attribute values to numbers for calculations, use parseFloat() or parseInt() ?
[...document.querySelectorAll("a")].forEach(a => {
const stringValue = a.dataset.value;
const numericValue = parseFloat(stringValue);
console.log("Original: %s (type: %s)", stringValue, typeof stringValue);
console.log("Converted: %s (type: %s)", numericValue, typeof numericValue);
console.log("---");
});
The output shows the conversion from string to number ?
Original: 6.0 (type: string) Converted: 6 (type: number) --- Original: 6.5 (type: string) Converted: 6.5 (type: number) --- Original: hello (type: string) Converted: NaN (type: number) ---
Conclusion
HTML5 data-* attributes always store values as strings, requiring explicit conversion to numbers using parseFloat() or parseInt() when performing numeric operations.
