tags:

views:

3811

answers:

3

The following two forms of jQuery selectors seem to do the same thing:

  • $("div > ul.posts")
  • $("div ul.posts")

which is to select all the "ul" elements of class "posts" under "div" elements.

Is there any difference?

+4  A: 

The first only selects ul.posts whose parentNode is div.

The second would also select:

<div>
    <blockquote>
        <ul class="posts"></ul>
    </blockquote>
</div>
eyelidlessness
+13  A: 

Concerning $("div > ul.posts"), only direct descendants of DIVs will be selected.

<div>
    <ul class="posts"> <!--SELECTED-->
        <li>List Item</li>
        <ul class="posts"> <!--NOT SELECTED-->
            <li>Sub list item</li>
        </ul>
    </ul>

    <fieldset>
        <ul class="posts"> <!--NOT SELECTED-->
            <li>List item</li>
        </ul>
    </fieldset>

    <ul class="posts"> <!--SELECTED-->
        <li>List item</li>
    </ul>
</div>

while $("div ul.posts") will select all descendants matching the criteria. So all and any ul.posts will be selected, whatever their nesting level is as long as somewhere along the chain, they are within a div.

Andrew Moore
You have comment-deleting magic. But gg for fixing it.
eyelidlessness
Sorry for deletion, the comment was no longer relevant ;)
Andrew Moore
I was just surprised you were able to delete it. It looks like you can delete comments under your own posts, news to me! Take care.
eyelidlessness
I wish the jQuery documentation was as clear as this. Thanks.
Jabes88
A: 

Oh. So "ancestor descendant" refers to all specified elements under a parent, no matter how deeply nested

While "parent child" refers only to the first specified element even if it occurs again somewhere else under the parent

robbysalz