Here is the Explanation in detail.
Use a class when you want to consistently style multiple elements throughout the page/site. Use the ID when you have a single element on the page that will take the style. class is a type of item and id is the unique name of an item.
EDIT:
CSS doesn't care
Regarding CSS
, there is nothing you can do with an ID
that you can't do with a Class
and vice versa. I remember when I was first learning CSS
and I was having a problem, sometimes I would try and troubleshoot by switching around these values. Nope. CSS
doesn't care.
Javascript cares
JavaScript
people are already probably more in tune with the differences between classes
and ID's
. JavaScript depends on there being only one page element with any particular, or else the commonly used getElementById
function wouldn't be dependable. For those familiar with jQuery
, you know how easy it is to add and remove classes
to page elements. It is a native and built in function of jQuery
. Notice how no such function exists for ID's
. It is not the responsibility of JavaScript
to manipulate these values, it would cause more problems than it would be worth.
EDIT2:
The Documentation clearly shows that HTML required the ID attribute to be unique in a page:
This attribute assigns a name to an element. This name must be unique in a document. If you have several elements with the same ID, your HTML is not valid.
So in JavaScript
, getElementById()
should only ever return one element. You can't make it return multiple elements.
Well, you can have more than one element with the same ID, but you shouldn't - because the consequences of doing so is unpredictable, due to differences between browsers.