How to select all elements with a particular ID in jQuery?
Solution 1:
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]")
Solution 2:
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'
Solution 3:
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.
Solution 4:
Try this for selecting div by first id
$('div[id^="c-"]')
Solution 5:
$("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