...">

JQuery loop though two levels of elements

I have 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 am trying to check if my div will contain a specific element. I need to loop over each block and then get each element.

What I still have

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

      

This is great because it will return all blocks that have elements. But I need something like lines

    $('.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?

+1


a source to share


4 answers


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



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

      

+2


a source


I hope you mean this:



$('.block').each(function(){
    $(this).find('div').each(function(){
        //do your stuff
    });
});

      

+3


a source


I would build a selector inside a 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            
     });
 });

      

+2


a source


Have you tried using

$("#" + this)

      

?
He used basically every jquery documentation example (Harshat already posted ... too slow, sob)

+1


a source







All Articles