Find Which Nth Child A Div is Within Another Div

Finding the solution to this will yield a solution to a higher level problem that I have

<div>
  <div class='childDiv'></div>
  <div class='childDiv'></div>
  <div class='childDiv'></div>
</div>

var childrenDivs = document.querySelectorAll('childDiv');

childrenDivs.forEach(function(value) {
  console.log('This is child number: ' + [insert code]);
});

I want it to output

This is child number: 1
This is child number: 2
This is child number: 3

I can’t figure out how to find the child position of value. Is this possible?

2 thoughts on “Find Which Nth Child A Div is Within Another Div”

  1. childrenDivs.forEach(function(value, i) {
      console.log('This is child number: ' + (i + 1));
    });
    

    Higher-order functions like forEach(), generally return the iterator (aka the index of current value in the array) as the second and optional parameter.

    Since arrays are indexed starting from 0, but we want to start from 1, we need to add always 1 to the iterator before logging it into the console.

    Reply

Leave a Comment