Reputation: 9986
Duplicate:
Sometime, when I like to make a selection a add an ID (unique) to something (images) and i used jquery to do domething when hover or click.
But the same thing can be done with classes. I understand that class is for a lot of thing (let's say class="selected") but when a class is added to something, I can trigger a jQuery action with that class insted of ID...
So the question is, what is "the right way" to use class and ID if I can accomplish anything and everything with both !
Upvotes: 3
Views: 2038
Reputation: 117333
An ID uniquely identifies an element within the entire document, whereas a class name is like a 'tag' - many tags can be added to an element, and the tags can be re-used.
Here's a comparison list:
http://example.com/mypage.htm#someid
. It is not possible to do this with classes.document.getElementById('someid')
(or $("#someid")
in jQuery). Note that libraries like jQuery make it possible to find elements by their class name too, but it's not nearly as efficient.Other properties of IDs
document.getElementById()
. For instance, a CSS selector based on that ID may match multiple elements as if it were a class. This is a really messy situation and you should never rely on it. I'd be happy if browsers stopped trying to support this.Upvotes: 0
Reputation: 38378
The simple difference between the two is that while a class can be used repeatedly on a page, an ID must only be used once per page. Therefore, it is appropriate to use an ID on the div element that is marking up the main content on the page, as there will only be one main content section. In contrast, you must use a class to set up alternating row colors on a table, as they are by definition going to be used more than once.
IDs are an incredibly powerful tool. An element with an ID can be the target of a piece of JavaScript that manipulates the element or its contents in some way. The ID attribute can be used as the target of an internal link, replacing anchor tags with name attributes. Finally, if you make your IDs clear and logical, they can serve as a sort of “self documentation” within the document. For example, you do not necessarily need to add a comment before a block stating that a block of code will contain the main content if the opening tag of the block has an ID of, say, "main", "header", "footer", etc.
Upvotes: 6
Reputation: 11308
The difference is, that an ID is something unique to a document so it should be only used for one element on a given HTML page.
Classes on the other hand are more like categories of elements. For example if you take a view on a single weblog post where you usually have the comments made to this weblog entry showing up right below it, you could give all these comments the class "comment" and the single weblog entry the ID "entry".
Upvotes: 2
Reputation: 1856
A HTML ID may only be applied to a single element, whereas a class can be used on many, which makes it more flexible.
Upvotes: 1