Tutorial :Jquery toggling each and every div with same id



Question:

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)

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

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


Solution:1

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:

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


Solution:2

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


Solution:3

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:

#id
Matches a single element with the given id attribute.

http://docs.jquery.com/Selectors/id#id

You should switch the body2010 id to a class attribute.


Solution:4

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.


Solution:5

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

You should use classes for this type of DOM query.


Solution:6

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
Previous
Next Post »