Hacker News new | ask | show | jobs
by sametmax 3021 days ago
Well if what you style is the main content/header/footer area, and there is should only be one of it per page, using an id is a good way to enforce it as well as document it.

If you made it a class, I would assume I can reuse it elsewhere.

Now it's ony true for stuff you can't reuse, but unless you are building a boostrap competitors, there are actually a lot of things you never reuse in a real website.

2 comments

Once I needed to make an internal IE addon to listen for certain elements being selected on pages outside of our control. (to ensure we never collected sensitive data for compliance reasons, long story. Trust me it makes more sense in context than it does in a single paragraph.)

My co-worker wanted to grab by id and attach listeners, but I was convinced that wouldn't work. I wanted to listen at the top level and filter down by id/class/etc...

The first production test was <redacted>.com/login. It had a login widget on the navbar and a login widget in the main content section. Both the username and the password field had the same id in the navbar and the content. So the addon did the right thing on the navbar, but not in the content, and we had to go back and redo it thanks to id reuse.

My point is, elements with ids are rarely unique. I've never regretted using a class instead of an id. I've regretted using an id instead of a class. And I really regretted third parties using ids instead of classes.

Please don't use ids. Your unique elements won't be for long, I guarantee it.

A friend once told me about a girl in their cs 101 class, who learned about arrays, and proceeded to make every variable an array. When queried, she responded, "I might end up realizing I need a multiple of the variable, and this way I won't have to change anything when I do".
Did she then go on to create jQuery? Because that concept (with a touch of functional inspiration) is one of the underlying ideas behind the library and why it was considered so much easier to work with than the DOM API.

I get where you're coming from, but I don't think it's a good reason to avoid classes. That's what they're there for.

Not at all; some simple effects like a stick-to-the-top header usually require cloning such element using JavaScript; and even if such effects are not needed right now they may be added in the near future, so no, there is not a single time where having an ID over a class makes sense.
Since I'm more of a backend dev, I'm going to take your advice and try it on my next work. Let's learn something today.