Posted 08th February 2016 by APSIS

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 something is said to be one of only two hard things in computer science. Sometimes, something as simple as selectors can stir a heated debate among passionate developers. Should selectors be semantic? Is it wise to visually group them in your markup? Should they be readable to humans or should they only cater to machines?

Plenty of people have plenty of opinions about this, and I really should take the time to add mine to the mix. But instead, I’d like to deal with a more specific, yet highly related subject.

One of my hard rules is to never use IDs for styling, as their dark force is just too powerful to be maintainable. On the other hand, IDs are perfect selectors for targeting an element with JavaScript. They are really specific, fast and basically made for this purpose. However, you can only use an ID once - even though 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') will surely get you all button elements on the page, it will also set you on a road of pain and frustration, because what you’re doing is giving that class a second job, besides styling. Which violates the separation of concerns principle. Which is bad. (At least, most of the time it’s bad.)

My solution - inspired by 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 a 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 are major factors in keeping a codebase sane over time, I always make sure to use the same convention, even if I am using ID.


By Hampus Persson, APSIS Front End Developer.

Want to see how our Development team works? Check out our video below to see how they deal with EPIC ideas and turn them into finished features, products and code!