HTML data attributes are useful for passing small pieces of information to JavaScript.
For example:
<button id = "save" data-enabled = "false" > Save </button>
Enter fullscreen mode
Exit fullscreen mode
You can read the value using dataset :
const button = document . querySelector ( "#save" ) ;
console . log ( button . dataset . enabled ) ; // "false"
Enter fullscreen mode
Exit fullscreen mode
The interesting part is that the value is a string, not a boolean.
So this doesn't work as you might expect:
if ( button . dataset . enabled ) { console . log ( "Button is enabled" ) ; }
Enter fullscreen mode
Exit fullscreen mode
The message will still be logged.
That's because "false" is a non-empty string, and non-empty strings are truthy in JavaScript.
The same thing happens with numbers.
<div id = "cart" data-count = "0" ></div>
Enter fullscreen mode
Exit fullscreen mode
const cart = document . querySelector ( "#cart" ) ;
console . log ( cart . dataset . count === 0 ) ; // false
console .…