Iterating Through N Level Children Iterating Through N Level Children javascript javascript

Iterating Through N Level Children


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);    });};


This question is awesome :-)

If you know your DOM is not too gigantic, you could just find all the descendants and filter out the ones that don't qualify:

var $parent = $('#parent');var $childrenWithinRange = $parent.find('*').filter(function() {  return $(this).parents('#parent').length < yourMaxDepth;});

After that, the jQuery instance "$childrenWithinRange" would be all the child nodes of that parent <div> that are within some maximum depth. If you wanted exactly that depth, you'd switch "<" to "===". I may be off by one somewhere.


You should be able to just do it with the all-selector(docs), the child-selector(docs) and multiple-selector(docs) like this:

Example: http://jsfiddle.net/mDu9q/1/

$('#start > *,#start > * > *,#start > * > * > *').doSomething();

...or if you only wanted to target the children 3 levels deep, you could do this:

Example: http://jsfiddle.net/mDu9q/2/

$('#start > * > * > *').doSomething();

Both of these selectors are valid for querySelectorAll, which means big performance boost in supported browsers.