Skip to main content Accessibility Feedback

Prefixing JavaScript selectors to avoid conflicts

Andrew Boorstein, one of the students in my Vanilla JS Slack channel asked:

Do you ever prefix your JavaScript hook classes with js- or something similar, so that changing a class name for styling purposes doesn’t inadvertently break your JS?

I absolutely do prefer to keep my selectors (as in, the hooks I use to target the elements I use in my scripts in plugins) unique to my script and not used for styling purposes. This frees me (and people who use my plugins) to style elements however the wish without worrying about breaking my scripts.

For a while, many folks recommended prefixing selector classes with .js- so that everyone knew they were used for JavaScript purposes. You’d end up with something like:

<div class=".collapse .js-collapse">
    Some content...
</div>

<script>
    var elem = document.querySelector('.js-collapse');
</script>

I actually don’t use classes for JS targets anymore, instead relying on data attributes.

I like them better because their entire purpose is for JS to hook into and grab data from (though they can now be used by CSS too). I might do something like this:

<div class=".collapse" data-collapse>
    Some content...
</div>

<script>
    var elem = document.querySelector('[data-collapse]');
</script>

This completely separates classes, which are intended from styling, from what I use to target elements with JavaScript.