Search code examples
javascriptchildren

Javascript how to loop child element of children


I want to read an element's children and for each of the children, read their children.

I have done this but do not understand why it does not work:

var myElement = $('.a-container');
var myChildren = myElement.children();

for(var i = 0; i < myChildren.length; i++) {
     var myGrandChildren = myChildren[i].children();
}

The error I get is myChildren[i].children() is not a function.

Is this not how to achieve what I'm trying to do?


Solution

  • You need to select the element inside the loop:

    myGrandChildren = $(myChildren[i]).children();
    

    Although in this case, jQuery.eq is more suitable:

    myGrandChildren = myChildren.eq(i).children();