0

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.

2 Answers 2

5
$('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
});
Sign up to request clarification or add additional context in comments.

3 Comments

and within that function, this.attr("id")
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.
@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
2

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

6 Comments

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 - Wrong. Have a read of the documentation docs.jquery.com/Utilities/jQuery.map e will be element. Try it out on jsbin.com
The second argument (which hasn't been given) would be the index
@Russ, how right you are, my appologies, I mistakenly read this as if it were $('div.fruit').map(callback), which behaves as I mentioned (docs.jquery.com/Traversing/map#callback).
@Brett- no worries! Apologies if I came across terse, it's a bit of a challenge writing long replies on the iPhone :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.