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!
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.
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.
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);
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With