4

Based on the different answers received, the only solution using jQuery without implementing our own selector function is a basic selector with ":first" or followed by ".eq(0)" for jQuery.

I wanted to know if their were any kind of max depth option or a function like "get only the first result then return it" but it seems it's not available in jQuery since even :first in the selector does not seem to be faster that a call to .eq(0) Thanks for all the comments.


Original post:

I'm wondering if a function like "closest" is available for the children elements.

Let's say I have an html structure like that:

div.container > [* some elements, I can't use children()] > div.sub1 > div.sub2 > div.sub1 > [other various children elements]

If I want the first div.sub1 I'm doing something like:

$("div.container").find("div.sub1").eq(0)

The problem is that we cannot specify a "max depth" so it will be searched in ALL the children. I see it as a performance issue.

I'm talking about "max depth" because I could list the possibles selectors cases but it would be a long list, about 6-10 items depending on the case.

Anyone has a solution for this?

Thank you

4

1 回答 1

7

您可以通过组合不同数量的子选择器 ( >) 和通配符 ( *) 来获得它:

// max-depth: grand-children
$('.container').find('> .sub1, > * > .sub1').first();

// max-depth: great-grand-children
$('.container').find('> .sub1, > * > .sub1, > * > * > .sub1').first();

而且,由于硬编码可能相当乏味,您可以使用自定义方法为您构建选择器:

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

示例:http : //jsfiddle.net/V82f3/2/


主要缺陷是它仅限于相对简单的选择器(或者可能仅限于单个选择器):

$('.container').findAtDepth('.sub1, .sub2', 3).first();

这将.sub1在最大深度 3 处搜索,但.sub2在任何深度处搜索。

于 2012-01-25T18:58:41.973 回答