1

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?

guagay_wk
  • 26,337
  • 54
  • 186
  • 295

6 Answers6

6

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 
Community
  • 1
  • 1
Jacob G
  • 13,762
  • 3
  • 47
  • 67
1

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.

Starfish
  • 3,344
  • 1
  • 19
  • 47
1

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.

Jonas
  • 2,139
  • 17
  • 38
1

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.

temarsden
  • 332
  • 5
  • 16
1

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.

Lyall
  • 1,367
  • 3
  • 17
  • 42
1

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"

boszlo
  • 1,144
  • 10
  • 14