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

Viewed 142797

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

I would use Different IDs but assign each DIV 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 reconstruct the IDs based off of the return of jQuery('.countdown').length


Ok what about adding multiple classes to each countdown timer. IE:

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

That way you get the best of both worlds. It even allows repeat 'IDS'

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.

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.

Related