There's quite a few questions on Stack Overflow about id
vs class
but these questions are nearly always in relation to CSS - and the generally accepted answer is to use classes to style a particular set of elements, and ids for specific instances. Makes sense, fair enough.
I'm finding however that as I do more and more Javascript/jQuery/ajax, that approach is starting to become less clear cut and I'm finding situations where semantically elements should be given ids, but because there could be multiple instances I'm supposed to use classes.
Here's an example of what I mean:
Take a look at the toolbar on Stack Overflow's markdown question editor - each button has an ID to uniquely identify it. Makes perfect sense - it's one button that performs a specific function and there's probably script hooked to it based on that id.
Now imagine that I'm building a rich web app and there's a page that has two tabs each with a markdown editor on it. Does this mean that the toolbar buttons should now be using classes to identify them?
This just seems wrong.
Another example: I'm working on a photo gallery site that has a little toolbar overlaid on each photo. Convention says that because there's multiple instances of these buttons I should use classes. Really?
So my questions are....
The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.
In contrast to the class attribute, which allows space-separated values, elements can only have one single ID value.
ID selectors are similar to class selectors. They can be used to select any HTML element that has an ID attribute. However, each ID can be used only once within a document, whereas classes can be used as often as needed.
You cannot have multiple IDs for a single div tag. There is never any need for multiple ids on the same tag since ids are unique either one would serve to uniquely identify that specific tag provided you first get rid of the other id which is stopping things working.
Classes mean is a ... (indefinite) IDs mean is the ... (definitive)
"This div is a photo-toolbar. There can be more like it." Makes sense, I would use a class.
I wouldn't necessarily ID toolbar buttons, unless I was sure that there can only be one instance of that toolbar on the page. In the case with StackOverflow's markdown editor, I also think these should be classes for more flexibility (the whole editor can be wrapped in a unique ID, like #answer-editor, or #comment-editor) instead.
Browsers are quite flexible in what they accept, but that doesn't mean the standards should be broken.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With