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

I am trying to select all <div> with the same ID in jQuery. How to do it?

I tried this and it did not work

 jQuery('#xx').each(function(ind,obj){ //do stuff; }); 
+60
jquery css-selectors
May 24 '09 at 1:16
source share
7 answers

I would use different identifiers, but assigned each DIV to the same class.

 <div id="c-1" class="countdown"></div> <div id="c-2" class="countdown"></div> 

This also has the added benefit of being able to recover identifiers based on jQuery return ("countdown"). length




Well, adding a few classes to each countdown timer. IE:

 <div class="countdown c-1"></div> <div class="countdown c-2"></div> <div class="countdown c-1"></div> 

Thus, you get the best of both worlds. It even allows you to repeat "IDS"

+36
May 24 '09 at 1:22
source share

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

When you use

 jQuery("#elemid") 

it selects only the first item with the given ID.

However, when you select by attribute (for example, id in your case), it returns all the relevant elements, for example:

 jQuery("[id=elemid]") 

This, of course, works for selection by any attribute, and you can further refine your choice by specifying the appropriate tag (for example, div in your case)

 jQuery("div[id=elemid]") 
+366
Jul 19 '11 at 9:02
source share

Your document should not have two sections with the same identifier. This is invalid HTML , and as a result, the underlying DOM API does not support it.

From the HTML standard :

id = name [CS] This attribute assigns the name of the element. This name must be unique in the document.

You can assign different identifiers for each div and select them with $('#id1, #id2) . Or assign the same class to both elements (e.g. .cls ) and use $('.cls') to select both of them.

+36
May 24 '09 at 1:19
source share

$("div[id^=" + controlid + "]") will return all controls with the same name, but you must make sure that the text should not be present in any of the controls

+3
Apr 15 '13 at 14:56
source share

Can you assign a unique CSS class to each individual timer? This way you can use a selector for the CSS class that works great with multiple div elements.

+2
May 24 '09 at 1:22
source share

You can also try wrapping two divs in two divs with unique identifiers. Then select the div on $("#div1","#wraper1") and $("#div1","#wraper2")

Here you go:

 <div id="wraper1"> <div id="div1"> </div> <div id="wraper2"> <div id="div1"> </div> 
+1
Aug 26 '10 at 12:10
source share

Try this to select div first id

 $('div[id^="c-"]') 
+1
Jan 08 '13 at 15:21
source share



All Articles