DA.
DA.

Reputation: 40671

Selecting first instance of class but not nested instances via jQuery

Given the following hypothetical markup:

<ul class="monkey">
    <li>
        <p class="horse"></p>
        <p class="cow"></p>
    </li>
</ul>

<dl class="monkey">
    <dt class="horse"></dt>
    <dd class="cow">
        <dl>
            <dt></dt>
            <dd></dd>
        </dl>
        <dl class="monkey">
            <dt class="horse"></dt>
            <dd class="cow"></dd>
        </dl>
    </dd>
</dl>

I want to be able to grab the 'first level' of horse and cow classes within each monkey class. But I don't want the NESTED horse and cow classes.

I started with .children, but that won't work with the UL example as they aren't direct children of .monkey.

I can use find: $('.monkey').find('.horse, .cow') but that returns all instances, including the nested ones.

I can filter the find: $('.monkey').find('.horse, .cow').not('.cow .horse, .cow .cow') but that prevents me from selecting nested instances on a second function call.

So...I guess what I'm looking for is 'find first "level" of this descendant'. I could likely do this with some looping logic, but was wondering if there is a selector and/or some combo of selectors that would achieve that logic.

UPDATE:

Here's what I ended up with:

$('.monkey')
    .children('.cow')
        ...do something...
    .end()
    .children('li')
        .children('.cow')
            ...do something...
        .end()
    .end()

Seems verbose/hacky but seems to work.

Upvotes: 3

Views: 1991

Answers (4)

John Hartsock
John Hartsock

Reputation: 86882

Use the children, as it give you the immediate child elements.

$(".monkey").children(".horse, .cow, li > .horse, li > .cow")

Edited

$(".monkey, .monkey > li").children(".horse, .cow")

Upvotes: 3

Genady Sergeev
Genady Sergeev

Reputation: 1650

This is the correct selector that will allow you to return only the first children of both li and dt elements

var selection = $(".monkey > * > .horse, .monkey > * > .cow");

Upvotes: 0

Michal
Michal

Reputation: 995

Maybe something like this?

$('.monkey>.horse, .monkey>.cow')

That should select just immediate children of .monkey, and you can filter out which .monkey object you want.

Upvotes: 0

derek
derek

Reputation: 4886

$('.monkey .horse:first')

http://api.jquery.com/first-selector/

Upvotes: 0

Related Questions