Tutorial :Jquery toggling each and every div with same id


I want to toggle a bunch of divs that each have the same id. My current jquery code only toggles one div. (I've tried using a mixture of .next and .parent.next, but haven't found anything yet)


So: There would be multiple divs with a '#body2010' id. I want to toggle all of those.


Duplicate ID names are invalid. You should convert them to classes. jQuery will only match the first matching element for ID tags whereas it would return an array of all class matches. You would then do:



You shouldn't have more than 1 element with the same ID in a document - use the class attribute instead.


ID's should be unique. JQuery knows that, so when you're searching for an element with a specific ID, jQuery will only return one element.

from jQuery docs:

Matches a single element with the given id attribute.


You should switch the body2010 id to a class attribute.


Knowing nothing about jQuery, I believe an ID should be unique and if you have multiple divs with the same ID, you should be using a class.


ID, as you know, stands for 'identifier'. IDs are unique in all contexts.

You should use classes for this type of DOM query.


jQuery will toggle only the first of those elements since ID's are supposed to be unique on a page. You will get a better result if you assign a class name to each of those divs and use that to toggle.

$('.body' + id).toggle('400');  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »