Iterating Through N Level Children

Posted by bobber205 on Stack Overflow See other posts from Stack Overflow or by bobber205
Published on 2011-01-17T22:19:45Z Indexed on 2011/01/17 22:53 UTC
Read the original article Hit count: 116

Filed under:
|
|

This seems like something neat that might be "built into" jQuery but I think it's still worth asking.

I have a problem where that can easily be solved by iterating through all the children of a element. I've recently discovered I need to account for the cases where I would need to do a level or two deeper than the "1 level" (just calling .children() once) I am currently doing.

jQuery.each(divToLookAt.children(), function(index, element)
    {
        //do stuff
    }
    );  

This is what I'm current doing. To go a second layer deep, I run another loop after doing stuff code for each element.

jQuery.each(divToLookAt.children(), function(index, element)
{
     //do stuff
    jQuery.each(jQuery(element).children(), function(indexLevelTwo, elementLevelTwo)
    {
        //do stuff
    }
    );  
}
);

If I want to go yet another level deep, I have to do this all over again.

This is clearly not good. I'd love to declare a "level" variable and then have it all take care of. Anyone have any ideas for a clean efficient jQueryish solution?

Thanks!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery