Last month, I was looking through some of my team’s code and noticed that a LOT of the HTML was using the “id” attribute. I use to work on the Web UI Framework when I was with IBM’s Jazz, and this code really jumped out to me because of how problematic that attribute can be when creating reusable UI widgets.
When one is tasked with writing reusable HTML code, I recommend to never use the id attribute. This is not because the attribute itself is a problem, but because of how the code will be used by your consumers. From the definition of the id attribute on W3 (emphasis mine):
> This attribute assigns a name to an element. This name must be unique in a document.
To resolve this problem, I recommend applying a namespaced class name to your html. For example, assume that I have a widget called “myModal” that contains a button:
<button class="com-tacoCorp-myModal-btn btn">Submit</button>
Now, if you’re worried about CSS selector performance (because using the #id selector is fast), be sure to check out the following articles for some alternative ways to write performant CSS rules:
Lastly, I must note that I believe this rule of thumb will help you most of the time, but there WILL be situation where the use of the “id” attribute are beneficial. For example, if you have a widget that may occur multiple times on a page (e.g. a hover popup), you may want to try to reuse those widgets instead of creating and destroying them each time they need to appear. Having an id (e.g. com-tacoCorp-myWidget_1) will help you find specific instances of the widget you wish to reuse. However, please note how I still use namespacing to help prevent collisions.
tl;dr Never use the id attribute if you EVER think your widget is going to be reused, unless you have a good reason to. Sticking with just classes in your web code will take you a long way.