views:

1096

answers:

4

I have some html that looks like this:

<div class="block">
    <div id="item1"></div>
    <div id="item2"></div>
</div>

<div class="block">
    <div id="item3"></div>
</div>

I'm trying to check to see if my div will contain a specific element. I need to loop though each block, then get each item.

What I've got so far

    $('.block:has(div)').each(function() {
         // do something with the block
    });

Which is great, because it will return all the blocks that have items in them. But I need something along the lines of

    $('.block:has(div)').each(function() {
             $('current place in loop' + li).each(function() {
                  // do something with each item element, before the block loop has finished
             });
    });

Any ideas?

+3  A: 

I hope you mean this:

$('.block').each(function(){
    $(this).find('div').each(function(){
        //do your stuff
    });
});
Here Be Wolves
Yep that's exactly what I did mean, works as I thought it should :)
Tom
be aware that that will find all <div> elements under the parent element, at any level. Use children() to get direct children only.
samjudson
@samjudson thanks for the correction.
Here Be Wolves
+2  A: 

I'm not 100% sure if this answers what you are asking, but wouldn't the following work:

$('.block:has(div)').each(function() {
  $(this).children('div').each(function() {
    // do something with each item element, before the block loop has finished
  });
});
samjudson
+1  A: 

Did you tried using

$("#" + this)

? It's used in the main each example of jquery documentation (harshath has already posted... too slow, sob) (can't submit the link to the documentation, not enough rep)

MaLKaV_eS
+2  A: 

I would build the selector within the nested each, or use find:

 $('.block:has(div)').each(function() {
     $('#' + this.id +  ' li').each(function() {
         //do stuff on list item            
     });
 });

OR

 $('.block:has(div)').each(function() {
     $(this).find('li').each(function() {
         //do stuff on list item            
     });
 });
karim79