Class for Show, ID for (win)Dow

As I strive to be a diligent and disciplined developer, I am always looking for ways to improve my coding methods and development processes. I tend to take algorithmic approaches to methodology. I have thought a lot recently about proper use of Classes and IDs in writing my HTML, and there has never before been a black and white answer to when I should use which.

Class or ID?

In general, most developers tend to stick with the classic definition of Class and ID. Classes are typically used when an element might appear more than once on a page so that the CSS only need be written once to affect all elements with the same class. IDs are typically used when an element is unique to a page and will only be used once on that page.

The aforementioned definitions of Class and ID usually cover most of the bases. However, there have been enough times when I thought I should apply an ID to a seemingly unique element only to realize I want to reuse it later on on another element, warranting giving the decision process a second thought. I am still a fairly new front-end developer, but now that I have been spending a great deal more time working with JavaScript, I have found a new solution.

Classes for Style, IDs for JS and the Window

Besides their assigned definitions, what are the real differences between Classes and IDs in practice? Really, the only difference is the fact that an ID can be used as a “hash value” for a URL. This means that www.myurl.com#my-section will load www.myurl.com and will automatically scroll the window down to the element with the ID of #my-section.

OK, so the browser cares which attribute you use, but what about the CSS? No. CSS doesn’t care whether you use a Class or an ID as long as you match the dot or hash symbol with the appropriate attribute in the HTML. And JavaScript? Well, JS does care a bit. JS knows that IDs are to be unique and that Classes should be grouped together, so when I need to access a single element with JS I’ll just create and ID for it. This does not eliminate the need to access multiple elements via their Class name, but the need for this seems to always come without ambiguity.

Styling an H1 tag? Use a Class. Use JS on one <nav> but not the other? Use an ID. Manipulate the JS Window Object to focus on an element? Again, use an ID. Maybe (hopefully) sometime in the future I will find a problem that makes me re-think my method. For now, this is my algorithm and I’m sticking to it!

Leave a Reply

Your email address will not be published. Required fields are marked *