Menu

A small thing about HTML data attributes
📰

A small thing about HTML data attributes

DEV Community: html·Soren Sterling·about 13 hours ago
#l2skyF7g
#devto2#devto#dev#save#cart
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.