views:

51

answers:

3

When i do something like :

$('#container').addClass("contract");

It only add class to the first div with id container

When i do something like :

$('.container').addClass("contract");

It adds the class to ALL the divs with class container

WHY ?

+1  A: 

Because id attribute has to be unique in HTML document. So there is no need to search for any others eelements with id="abc" when you find a first one.

Crozin
+1  A: 

An element's ID attribute should uniquely identify it. A class attribute may be applied to more than one element. As ID is unique, jQuery will only apply it to the first element that matches that.

Owen
+1  A: 

Every element ID must be unique. An ID points to one and only one attribute. Jquery or any other framework would not even consider that you might have more than one element with a particular id. All your elements need to have a different id. Javascript and the DOM expect this (document.getElementByID for example will return just one element, and might now work at all if the ID is duplicated). Everything expects this.

Patrick Karcher