JavaScript hooks in your markup

TL;DR;
Prepend all your JavaScript hooks with js-, no matter if it’s a class or an id.

Naming thing is said to be one of the two hard things in computer science and something as simple as selectors can sometime stir a heated debate among passionate developers. Should selectors be semantic? Is it wise to visually group them in your markup? Should they be human readable or should they only cater to machines?

I have plenty of opinions to offer here, and I really should take the time to write something up about my philosophy. But this post will be much shorter and deal with a more specific, yet highly related subject. One of my hard rules is to never use id for styling, their dark force is simply to powerful to be maintainable. On the other hand, id are perfect selectors for targeting an element with JavaScript. They are really specific, really fast and are basically made for this stuff.

However, you can only use an id once and sometimes you need to target more than one element. Typically you would turn to classes, and often you would just pick a class that is already available on the element in question, like .Button. And while document.querySelectorAll('.Button') surely will get you all button elements on the page it will also you start you down a road of pain and frustration. What you’re doing is that you’re giving that class a second job, beside styling. What you’re doing is violating the separation of concerns principle. And that’s bad. At least most of the time.

My solution, that I picked up from the excellent Harry Roberts, is to make sure to always have a separate class for JavaScript hooks, and to always prepend it with js-. So to target the button above I would give it an additional class along the lines of js-button. That way it’s easy for someone reading my markup to distinguish styling classes from classes hooked by scripts.

And since consistency and standards is a major factor in keeping a codebase sane over time I make sure to use the same convention even if I’m using id.