|
I feel like you're still thinking small in terms of attributes, and big in terms of values. Many many values all crammed into one attribute (class), but the reality is you can invent infinite (∞) data attributes. There's literally no need for you to format the values as a list of space-separated values…unless you want to. But if you don't want to, there's no need. Consider this, instead of targeting something with classes like this .active.demo, and setting it like this el.classList.add('active')
el.classList.add('demo')
You would NOT need to do something like this to use data attributes, [data-example~=active][data-example~=demo] and to set it like this: if (!el.dataset.example.split(' ').includes('demo')) {
el.dataset.example += ' demo'
}
You could instead easily set two attributes and test for their presence, even if they don't have values (or you're not using them) el.dataset.active = el.dataset.demo = true
And then you can target that in CSS with [data-active][data-demo]. To remove them later is just as simple: el.dataset.active = false
And it's gone! Try to think BIG in terms of attributes, and small in terms of values. It's a lot nicer than trying to cram all of your values into just one attribute when you literally have infinite attributes available to work with!Not only do you have infinite attributes to work with, but you can Using classes as your only way to target styles, and ignoring the other aspects of how CSS selectors can target elements is like picking up a guitar and trying to play a song, but only plucking one string. You might be making it harder on yourself to get the job done, and the result isn't any better for the effort. EDIT: Just for kicks, have you ever considered the flexibility of what data types you can set as an attribute value other than a space separated list of strings? Try this: // set JSON to attribute value
document.documentElement.dataset.example = JSON.stringify({one: 1, two: 2})
// get JSON from attribute value
JSON.parse(document.documentElement.dataset.example)
You can even stick a bit of JSON there as the attribute value, which can be parse/stringified by JS, is _easy_ to add or remove properties from and work with on the JS side (not requiring helper methods like classList), and is _still_ targetable by CSS once set on an element :D The possibilities are endless, the apparent limitations a lot of people butt up against are self-imposed. |