A Complete Guide to Data Attributes

I like using data attributes in my markup (data-*), CSS ([data-*]), and JS (el.dataset). This post on CSS-Tricks writes down exactly how I use them.

Especially the different type of attribute selectors are really powerful:


// Seven different types of CSS attribute selectors

// This attribute exists on the element
[value]

// This attribute has a specific value of cool
[value='cool'] 

// This attribute value contains the word cool somewhere in it
[value*='cool'] 

// This attribute value contains the word cool in a space-separated list
[value~='cool'] 

// This attribute value starts with the word cool
[value^='cool'] 

// This attribute value starts with cool in a dash-separated list
[value|='cool'] 

// This attribute value ends with the word cool
[value$='cool'] 

The contains selector becomes really powerful when building a JavaScript filter: such a CSS selector can be passed directly into document.querySelectorAll. The yielded result will immediately contain to correct selection, instead of looping over all items that and checking them one-by-one.

A Complete Guide to Data Attributes →

About the Author

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.