You can get this by combining the child selector ( > ) and the wildcard ( * ) in different quantities:
// max-depth: grand-children $('.container').find('> .sub1, > * > .sub1').first(); // max-depth: great-grand-children $('.container').find('> .sub1, > * > .sub1, > * > * > .sub1').first();
And, since this can be quite tedious for hard coding, you can use your own method to create a selector for you:
jQuery.fn.findAtDepth = function (selector, maxDepth) { var depths = [], i; if (maxDepth > 0) { for (i = 1; i <= maxDepth; i++) { depths.push('> ' + new Array(i).join('* > ') + selector); } selector = depths.join(', '); } return this.find(selector); }; $('.container').findAtDepth('.sub1', 3).first();
Exam: http://jsfiddle.net/V82f3/2/
The main disadvantage of this is that it is limited to relatively simple selectors (or, perhaps, only individual selectors):
$('.container').findAtDepth('.sub1, .sub2', 3).first();
This will search for .sub1 at a maximum depth of 3, but for .sub2 at any depth.
source share