How to select all elements with a particular ID in jQuery?

mark picture mark · May 24, 2009 · Viewed 132.6k times · Source

I'm trying to select all <div>s with the same ID in jQuery. How do i do it?

I tried this and it did not work

jQuery('#xx').each(function(ind,obj){
      //do stuff;
});

Answer

mydoghasworms picture mydoghasworms · Jul 19, 2011

Though there are other correct answers here (such as using classes), from an academic point of view it is of course possible to have multiple divs with the same ID, and it is possible to select them with jQuery.

When you use

jQuery("#elemid") 

it selects only the first element with the given ID.

However, when you select by attribute (e.g. id in your case), it returns all matching elements, like so:

jQuery("[id=elemid]") 

This of course works for selection on any attribute, and you could further refine your selection by specifying the tag in question (e.g. div in your case)

jQuery("div[id=elemid]")