<div class="expand"> Some content that can be collapsed or expanded. </div>
If it’s used only for targeting in JS, what happens if a well meaning developer sees that the class isn’t used in their CSS file and removes it to reduce some weight from the markup? If it’s used for both, what happens if someone decides to rename the class to fit a different CSS naming convention?
An early approach to solving this challenge
.js-, making it more explicit what it was used for.
<div class="js-expand"> Some content that can be collapsed or expanded. </div>
If you wanted to be really dogmatic about it, you would include both a
.js- prefixed and non-prefixed version, one used solely for styling, the other only for targeting with JS.
<div class="expand js-expand"> Some content that can be collapsed or expanded. </div>
I don’t like this approach
So what can you do instead?
Use data attributes
Data attributes exist solely to add additional information to an element. In the HTML spec, they have no defined meaning, which makes them incredibly flexible.
There are two approaches to this. One is to use a unique data attribute as your target.
<div class="expand" data-expand> Some content that can be collapsed or expanded. </div>
var expand = document.querySelectorAll('[data-expand]');
The other is to use an attribute like
[data-action] with a unique value.
<div class="expand" data-action="expand"> Some content that can be collapsed or expanded. </div>
var expand = document.querySelectorAll('[data-action="expand"]');