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

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;
});

This question is related to jquery css-selectors

The answer is


$("div[id^=" + controlid + "]") will return all the controls with the same name but you need to ensure that the text should not present in any of the controls


Your document should not contain two divs with the same id. 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 a name to an element. This name must be unique in a document.

You can either assign different ids to each div and select them both using $('#id1, #id2). Or assign the same class to both elements (.cls for example), and use $('.cls') to select them both.


Try this for selecting div by first id

$('div[id^="c-"]')

You could also try wrapping the two div's in two div's with unique ids. Then select the div by $("#div1","#wraper1") and $("#div1","#wraper2")

Here you go:

<div id="wraper1">
<div id="div1">
</div>
<div id="wraper2">
<div id="div1">
</div>

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]") 

Can you assign a unique CSS class to each distinct timer? That way you could use the selector for the CSS class, which would work fine with multiple div elements.