views:

163

answers:

2

Hi,

Suppose I have this:

<div id="apple" class="fruit"></div>
<div id="orange" class="fruit"></div>
<div id="grape" class="fruit"></div>
<div id="pear" class="fruit"></div>

How do I write a javascript function that can loop and print out all the fruit IDs with class "fruit"? Using JQuery.

+4  A: 
$('div.fruit').each(function(){
 //will loop through all divs with the class fruit.
 $(this).attr('id'); //will give you the id of the current div
});
Colin
and within that function, this.attr("id")
Frank Schwieterman
this.attr("id") is right!
TIMEX
this.id should also work?
Colin
this.attr('id') is incorrect, you need $(this).attr('id'); `this.id` will work as from the documentation "`this` == domElement". The `each()` callback will allow you to use two arguments, the first being the index in the result list, the second again being the dom element.
Brett Ryan
@Colin - yes, `this.id` would work too and would probably be more optimal since `this` is not being wrapped in a jQuery object inside each iteration
Russ Cam
+2  A: 

As printed out as comma separated list (ids is an array of the ids).

var ids = $.map($('div.fruit'), function(e) {
    return e.id;
});
document.write(ids.join(','));

Working Demo - click on the output tab to see the output.

Using the following would cater for there being <div class="fruit"> with no id

var ids = $.map($('div.fruit'), function(e) {
    return e.id? e.id : null;
});
Russ Cam
This is incorrect, since the callback functions first argument is the index to the element in the list, use `this.id` instead; or use a second argument to your callback function which will be the DOM element. Alternatively use `$(this).attr('id')`.
Brett Ryan
@Brett - Wrong. Have a read of the documentation http://docs.jquery.com/Utilities/jQuery.map e will be element. Try it out on http://jsbin.com
Russ Cam
The second argument (which hasn't been given) would be the index
Russ Cam
@Russ, how right you are, my appologies, I mistakenly read this as if it were `$('div.fruit').map(callback)`, which behaves as I mentioned (http://docs.jquery.com/Traversing/map#callback).
Brett Ryan
@Brett- no worries! Apologies if I came across terse, it's a bit of a challenge writing long replies on the iPhone :)
Russ Cam
lol, not a problem at all :) I am actually surprised with `$.map` as most callbacks in jQuery accept the index as the first argument.
Brett Ryan