The following two forms of jQuery selectors seem to do the same thing:
which is to select all the "ul" elements of class "posts" under "div" elements.
Is there any difference?
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: $().
The ("parent > child") selector selects all elements that are a direct child of the specified element.
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.
Concerning $("div > ul.posts")
, only direct descendants of DIV
s 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
.
The first only selects ul.posts whose parentNode is div.
The second would also select:
<div>
<blockquote>
<ul class="posts"></ul>
</blockquote>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With