Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery class within class selector

<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.

like image 435
fearofawhackplanet Avatar asked Sep 22 '10 08:09

fearofawhackplanet


People also ask

How do I select a specific class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How do I add a class name to a class selector?

To do this, start with the element name, then write the period (.) character, followed by the name of the class (look at Example 1 below). HTML elements can also refer to more than one class (look at Example 2 below).

How do you select all elements with the same class?

To select elements by a given class name, you use the getElementsByClassName() method: let elements = document. getElementsByClassName('className');


2 Answers

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.

like image 64
Andy E Avatar answered Sep 20 '22 17:09

Andy E


For this html:

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

This selector should work:

$('.outer > .inner')
like image 24
Sarfraz Avatar answered Sep 18 '22 17:09

Sarfraz