Lebovski
Lebovski

Reputation: 166

jQuery get only top level elements

I need to get only the first matched elements from my tree (if element was found no need to go deeper). The problem is that this element can be wrapped into nested divs, so I can't use > selector.
My code is like this:

<div id="root">
    <div class="sub">I need this element</div>
    <div>
        <div class="sub">I need this element</div>
    </div>
    <div class="sub">
        <div class="sub">I don't need this element</div>
    </div>
</div>

Can't find solution :(

Upvotes: 2

Views: 5541

Answers (4)

sanjay
sanjay

Reputation: 21

You would need the element or class which is above the first div, then specify {parent-selector} >

$('#root > div.sub').click(function(){
    // your code here
});

Upvotes: 2

RightSaidFred
RightSaidFred

Reputation: 11327

var level = $('#root'),
    subs;

do {
    level = level.children();
    subs = level.filter('.sub');
} while( els.length && !subs.length )

The subs variable will hold the result.

It's an efficient approach, and will work if your #root happens to have a .sub ancestor.

You could easily make it into a reusable function.

function firstLevelOf( root, selector ) {
    var level = $(root),
        result;

    do {
        level = level.children();
        result = level.filter(selector);
    } while( els.length && !result.length )

    return result;
}

Use it like this:

var subs = firstLevelOf( '#root', '.sub' );

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816462

If you can't use the child selector, try

$('.sub:not(.sub .sub)')

This selects only those .sub elements which are not descendants of other .sub elements.

Alternatively:

$('#root .sub').filter(function() {
    return $(this).parentsUntil('#root', '.sub').length === 0;
});

which also works if #root is inside a .sub.

Edit: Or see @RightSaidFred's comment for this case.

Upvotes: 5

jli
jli

Reputation: 6623

You can use:

$('.sub').parent().not('.sub').children().css('color', 'green');

which is a verbose version of:

$('.sub:not(.sub .sub)').css('color', 'green');

Edit: jsfiddle

Upvotes: 4

Related Questions