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; });
Here is a solution: You can use JQuery selector $("[id='idofelement']") to select all the elements with matching ID.
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.
In jQuery, you can select multiple elements by separate it with a comma “,” symbol.
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]")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With