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 ---
source share