Suppose I have this:
<div id="apple" class="fruit"&g开发者_JAVA百科t;</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.
$('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
});
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;
});
精彩评论