views:

265

answers:

5
<div id="div">
    <div> <!-- first level -->
        <div> <!-- second level -->
            <div>1.1</div> <!-- third level -->
            <div>1.2</div>
        </div>
        <div>
            <div></div>
            <div>2.2</div>
        </div>
    </div>
</div>

What are the jQuery selector expressions for selecting the followings:
1. div commented by first level
2. divs commented by second level
3. divs commented by third level

+2  A: 

Use the immediate child selector > in this case:

  • First level:
    • $("#div > div")
    • $("#div > *") (generic version)
  • Second level:
    • $("#div > div > div")
    • $("#div > * > *") (generic version)
  • Third Level:
    • $("#div > div > div > div")
    • $("#div > * > * > *") (generic version)

The equivalent generic is .children() without a selector as well, e.g.:

$("#div").children()
$("#div").children().children()
$("#div").children().children().children()
Nick Craver
+2  A: 

Exactly the same as the CSS selectors for them.

Edited for your new requirements:

#div > *
#div > * > *
#div > * > * > *
Matti Virkkunen
please see my comment
Saiful
+2  A: 
  1. $('#div > *') - This will select all tags that are a direct decedent of the element #div. Without using the child selector >, you would get all tags within the element #div, not just the first level.

  2. $('#div > * > *') - Same idea as #1

  3. $('#div > * > * > *')

wsanville
please see my comment
Saiful
+3  A: 

The key to all of these is either the > (child) selector or the children() method.

First level:

$("#div > div")...
$("#div").children("div")...

Second level:

$("#div > div > div")...
$("#div").children("div").children("div")...

Third level:

$("#div > div > div > div")...
$("#div").children("div").children("div").children("div")...

If you're not interested in a particular tag (eg div) then simply don't specify a selector to children(). For example, all second level elements:

$("#div").children().children()...
cletus
please see my comment
Saiful
A: 

they are true but for selecting specifically your first items, use this;

first level : $("#div").children("div:first-child")

Second level: $("#div:first-child").children("div:first-child").children("div:first-child")

Third level: $("#div").children("div":first-child).children("div:first-child").children("div:first-child")
spielersun