Given this sample markup (assuming a random number of elements between .outer
and .inner
:
-
You could use some css magic:
$('.outer>.inner')
Shold give you only first level of .inner
elements. :)
讨论(0)
-
$('.outer').children('.inner');
That would select any inner
that sits immediately below an outer
. I'm not really clear on which div you're trying to select for. Is it a, b, c, or d? Having something called outer nested within something called inner doesn't make a whole lot of sense. Maybe if you could provide a more specific example?
讨论(0)
-
I wonder why not to select .inner
at first, and then get closest
.outer
?
$inner = $('.inner');
$outer = $inner.closest('.outer');
in case some inner blocks could be not within outer blocks at all, use this first line instead
$inner = $('.outer .inner');
讨论(0)
-
Here's another option. Suppose you have the .outer
o
, this will select all inner
s under it:
o.find('.inner').not(o.find('.outer .inner'))
It should work identically to gnarf's answer, but a bit simpler.
First, it finds all inner
s under this outer
.
Next, remove all inners
that are descendants of other outers
Interactive working example: http://jsfiddle.net/Zb9gF/
Selector performance seems to be much better using this method as opposed to the .filter()
as well: http://jsperf.com/selector-test-find-not
讨论(0)
-
If assume correctly you want to select all .inner
that is beneath an .outer
, except if there is an .outer
inbetween, perhaps following will work (untested):
$('.outer:not(.inner):has(:not(.outer) .inner:not(.outer), > .inner:not(.outer))');
updated after test on OP example HTML at http://jsfiddle.net/cEwBT/1/
讨论(0)
-
If the .inner
are always direct children of .outer
s - children() is probably your best bet (jasongetsdown's answer)
If you need something that looks even deeper, you could do something like this:
var $outer = $('.outer').first(); // grab the first .outer
$outer.find('.inner').filter(function() {
// only if the closest parent .outer is the same as the .outer we are looking in
return $(this).closest('.outer').get(0) == $outer.get(0);
}).css('border','1px solid #000');
jsfiddle demo
讨论(0)