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