Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating Through N Level Children

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!

like image 405
bobber205 Avatar asked Jan 17 '11 22:01

bobber205


People also ask

How do you iterate a child?

To iterate over Children of HTML Element in JavaScript, get the reference to this HTML Element, get children of this HTML using using children property, then use for loop to iterate over the children.

How do you iterate through children in jquery?

each( (index, element) => { console. log(index); // children's index console. log(element); // children's element }); This iterates through all the children and their element with index value can be accessed separately using element and index respectively.


1 Answers

This is an awesome question because of the levels deep catch. Check out the fiddle.

Converted this to a plugin.

Activate

$('#div').goDeep(3, function(deep){ // $.fn.goDeep(levels, callback)
    // do stuff on `this`
});

Plugin

$.fn.goDeep = function(levels, func){
    var iterateChildren = function(current, levelsDeep){
        func.call(current, levelsDeep);

        if(levelsDeep > 0)
            $.each(current.children(), function(index, element){
                iterateChildren($(element), levelsDeep-1);
            });
    };

    return this.each(function(){
        iterateChildren($(this), levels);
    });
};
like image 108
Josiah Ruddell Avatar answered Nov 09 '22 00:11

Josiah Ruddell