Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }); 
like image 799
mark Avatar asked May 24 '09 01:05

mark


People also ask

How do I select all elements with the same ID?

Here is a solution: You can use JQuery selector $("[id='idofelement']") to select all the elements with matching ID.

How do you select element by id in jQuery?

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.

How do I find an element with a specific ID?

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.

Can you select multiple elements in jQuery?

In jQuery, you can select multiple elements by separate it with a comma “,” symbol.


1 Answers

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]")  
like image 108
mydoghasworms Avatar answered Oct 21 '22 21:10

mydoghasworms