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.