From your example:
$('ul li'); // Returns all 3 li's
// <li> Parent ... </li>
// <li> child1 </li>
// <li> child2 </li>
$('ul li:first'); // Returns the first li of all matching li's from above
// <li> Parent ... </li>
Assuming we have all three results from the first selector $("ul li")
, then the :first-child
will filter out any element from that list that is not the first child of it's parent. In this case, <li> child2 </li>
gets filtered out because it was the 2nd child of a <ul>
.
$('ul li:first-child'); // Returns all li's that are the first child of any ul
// <li> Parent .. </li>
// <li> child1 </li>
Also, for the first-child selector, the element has to be the very first child in the DOM, and not in the jQuery result set. For example, with the given structure:
<div>
<h1>First</h1>
<span>Second</span>
<span>Third</span>
</div>
the query below will yield 0 results as <span>
is not the first-child of div.
$("div span:first-child")
A good way to understand first-child
would be to think of it as a filter that will filter out any element in the current result set, if it is not the very first child of its parent.