Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between jQuery selectors "ancestor descendant" and "parent > child"

Tags:

jquery

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?

like image 383
pythonquick Avatar asked Oct 15 '08 04:10

pythonquick


People also ask

What are selectors in jQuery and how many types of selectors are there?

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors. All selectors in jQuery start with the dollar sign and parentheses: $().

What is a parent child selector?

The ("parent > child") selector selects all elements that are a direct child of the specified element.

What is jQuery descendant?

With jQuery you can traverse down the DOM tree to find descendants of an element. A descendant is a child, grandchild, great-grandchild, and so on.


2 Answers

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.

like image 79
Andrew Moore Avatar answered Sep 19 '22 17:09

Andrew Moore


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

The second would also select:

<div>
    <blockquote>
        <ul class="posts"></ul>
    </blockquote>
</div>
like image 23
eyelidlessness Avatar answered Sep 20 '22 17:09

eyelidlessness