I read that id
can only be used once in a html document while class
can be used multiple number of times. If this is the case, why don't programmers simply use class
all the time? Wouldn't this make things simpler?
6 Answers
A few reasons:
1: Id's are for targeting one element, while classes are for multiple
Example:
<div id="test">This is red</div>
<div class="test"></div>
<div class="test"></div>
#test{
background:red;
}
2: Id's overrule classes in CSS
Example:
<div class="test" id="test">Test</div>
#test{
background:red;//Overrides, even though it is higher in the document
}
.test{
background:blue;
}
3: Id's are used for anchor links in HTML
Example:
<a href="#test">Link to test</a>
<div id="test"></div>
4: Id's are easier to select with JavaScript
<div id="test"></div>
<div class="test"></div>
document.getElementById("test"); //returns the element
document.getElementsByClassName("test"); //returns a HTMLCollection, which is like an array
-
2Possibly typo in number 3 (`href="#test"`) – mr5 Aug 07 '15 at 14:45
-
1@mr5 thanks for pointing that out! will edit :D – Jacob G Aug 07 '15 at 14:47
I remember one of the things is that IDs have higher specificity than classes. There may be times when a declaration conflicts with another declaration. These conflicts are resolved using the Cascade rules. In simple terms, if a class selector and ID selector were to be in conflict, the ID selector would be chosen.

- 3,344
- 1
- 19
- 47
Sometimes you want exactly one element and not all elements with the same class. The class is to design a group of elements. The id is used to identify and modify a single element.

- 2,139
- 17
- 38
Sometimes you need to target a specific, unique, element not just an entire class of elements. the ID
attribute allows you to target unique elements.

- 332
- 5
- 16
ID can also be REFERENCED as many times as you want but the ID itself needs to be unique, the same way the class name does.
You can target a specific element with an ID but using a class you target everything with that class associated to it.
There is no limit to the number of times you can reference either an ID or a class within the HTML or CSS itself.

- 1,367
- 3
- 17
- 42
There are quite a few reasons:
higher specificity
you can use ids in links like http://mypage#section
you can combine ids with classes, eg
id="comment_id_700" class="comment"
...but there's a general rule: "if you don't need them don't use them"

- 1,144
- 10
- 14