mpdc
mpdc

Reputation: 3560

Using each() to loop over a specific parent's children

I have the following HTML structure:

<div class="parent">
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
</div>
<div class="parent">
    <div class="child">
    </div>
    <div class="child">
    </div>
</div>
<div class="parent">
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
    <div class="child">
    </div>
</div>

And my question is, during an each() loop of the parents, how can I then loop over that specific parent's children? This is the (unworking) code I have so far.

var parents = $('div.parent');
var children = $('div.child');

$(parents).each(function(index, value) {
    // do something
    $(children, parents + index).each(function() {
        //do something else
    });
});

The alternative option I suppose is to set the children variable within that first each(), but again I'm unsure how to do that.

Upvotes: 1

Views: 409

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is partly because you're selecting div.child globally in the children variable, and partly because you're trying to append an integer value (index) with a jQuery object (parents), which will not work.

To achieve what you require you need to get the children() of the current .parent element in the loop, which can be done by using the this keyword. Try this:

var $parents = $('div.parent');

$parents.each(function() {
  $(this).children().each(function() {
    console.log($(this).text());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div class="child">A-1</div>
  <div class="child">A-2</div>
  <div class="child">A-3</div>
</div>
<div class="parent">
  <div class="child">B-1</div>
  <div class="child">B-2</div>
</div>
<div class="parent">
  <div class="child">B-1</div>
  <div class="child">B-2</div>
  <div class="child">B-3</div>
  <div class="child">B-4</div>
</div>

Upvotes: 3

Related Questions