Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, get ID of each element in a class using .each?

I'm trying this to get the id of each element in a class but instead it's alerting each name of the class separately, so for class="test" it's alerting: t, e, s, t... Any advice on how to get the each element id that is part of the class is appreciated, as I can't seem to figure this out.. Thanks.

$.each('test', function() {     alert(this) }); 
like image 591
Rick Avatar asked Aug 15 '10 01:08

Rick


People also ask

How to get id value jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.

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 you target a class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How do I set the value of a element in jQuery?

The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.


2 Answers

Try this, replacing .myClassName with the actual name of the class (but keep the period at the beginning).

$('.myClassName').each(function() {     alert( this.id ); }); 

So if the class is "test", you'd do $('.test').each(func....

This is the specific form of .each() that iterates over a jQuery object.

The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t.

Using that form of $.each(), you would need to do it like this:

$.each($('.myClassName'), function() {     alert( this.id ); }); 

...which will have the same result as the example above.

like image 51
user113716 Avatar answered Oct 16 '22 23:10

user113716


patrick dw's answer is right on.

For kicks and giggles I thought I would post a simple way to return an array of all the IDs.

var arrayOfIds = $.map($(".myClassName"), function(n, i){   return n.id; }); alert(arrayOfIds); 
like image 20
jessegavin Avatar answered Oct 16 '22 23:10

jessegavin