tags:

views:

95

answers:

4

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.

A: 
$('.monkey .horse:first')

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

derek
:first returns the first element. Not a set of elements at that 'first' descendant level.
DA
+2  A: 

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")
John Hartsock
that's a good point. I suppose I could just decide that either they need to be direct children or grandchildren and leave it at that. That might be the best option.
DA
Hmm...well, it appears that descendant selectors don't work within a children() traversal.
DA
well try the modified version above
John Hartsock
A: 

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.

Michal
This will return the nested elements as well.
Genady Sergeev
The issue is that I am attaching the chain initially to the '.monkey' query. I'd rather not traverse the DOM a second time to get the children.
DA
A: 

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");
Genady Sergeev