47
<div class="outer">
     <div class="inner"></div>
</div>

how do I find the inner div here?

$container.find('.outer .inner')

is just going to look for a div with class="outer inner", is that correct?

so I tried

$container.find('.outer > .inner')

but that doesn't seem to be working.

Edit:

I know its easy to find with something like

$container.find('.outer').find('.inner')

but I'm looking for the kind of single selector syntax which reads better imho.

2
  • How is $container defined? Besides that, should use single selectors whenever possible. It is way easier to read if you do not have to search for the different selector parts all over the place. Commented Sep 22, 2010 at 8:34
  • "but I'm looking for the kind of single selector syntax which reads better imho." You should prefer the .find(...) way because it will be faster the more complex your selector gets or if you use an selector which is not supported by the browser. In this case sizzle will be used for selection which is/could be really slow in comparison to a splitted selector with .find(...). Commented Sep 22, 2010 at 9:30

2 Answers 2

90

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

Sign up to request clarification or add additional context in comments.

1 Comment

I had another mistake in my code which led me to think my selector wasn't working, but it was after all. Thanks for the explanation.
39

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.