Get the maximum depth of the selected node in the DOM using jQuery

I would like to calculate the maximum "depth" of the DOM tree structure (the length of the longest tree branch, taking into account its root). For instance:

<div class="group level0" id="group1"> <div class="group level1" id="group2"> <div class="group level2" id="group3"> <div class="group level3"> </div> </div> </div> <div class="group level1"> <div class="group level2"> </div> </div> </div> 

For example, the result for div#group1 will be 3. The result for div#group2 will be 2, and the result for div#group3 will be 1.

+4
source share
4 answers

Here:

 var calcDepth = function ( root ) { var $children = $( root ).children(); var depth = 0; while ( $children.length > 0 ) { $children = $children.children(); depth += 1; } return depth; }; 

Live demo: http://jsfiddle.net/WqXy9/

 calcDepth( $('#group1')[0] ) // => 3 calcDepth( $('#group2')[0] ) // => 2 
+6
source

This function will find the maximum depth in the DOM tree from the given root , tracking the tree only through nodes with a specific class :

 function getDepth(root, className) { var children = root.children('.' + className), maxDepth = 0; if (children.length === 0) { return maxDepth; } else { children.each(function() { var depth = 1 + getDepth($(this), className); if (depth > maxDepth) { maxDepth = depth; } }); } return maxDepth; } var root = $('#group1'); var className = 'group'; var depth = getDepth(root,className);​ 

Here's a demo with a slightly more complex DOM:

--- jsFiddle DEMO ---

0
source

Here's a non-recursive solution:

 function len(sel) { var depth = 0; $(sel + " :not(:has(*))").each(function() { var tmp = $(this).parentsUntil(sel).length + 1; if (tmp > depth) depth = tmp; }); return depth; } 

DEMO: http://jsfiddle.net/f2REj/

0
source
 jQuery.fn.depth = function() { var children = jQuery(this).children(); if (children.length === 0) return 0; else { var maxLength = 0; children.each(function() { maxLength = Math.max(jQuery(this).depth(), maxLength); }); return 1 + maxLength; } }; 

Demo: http://jsfiddle.net/7Q3a9/

0
source

Source: https://habr.com/ru/post/1433577/


All Articles