Selecting first instance of class but not nested instances via jQuery
Posted
by DA
on Stack Overflow
See other posts from Stack Overflow
or by DA
Published on 2010-05-06T15:15:35Z
Indexed on
2010/05/06
15:18 UTC
Read the original article
Hit count: 281
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.
© Stack Overflow or respective owner