I see that the comments answer the question fairly; but I would like to weigh in on one point raised by Ori Drori.
While the :first
selector is similar to :first-child
, there is an inherent difference.
Let us use the very example linked in the question:
<p>List 1:</p>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Tea</li>
</ul>
<p>List 2:</p>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Tea</li>
</ul>
<button>Click me</button>
When we run the following script :
$(document).ready(function(){
$("button").click(function(){
$("ul li:first").hide();
});
});
The item <li>Coffee</li>
present in List 1 gets hidden. However the one present in List 2 stays visible.
If instead, we were to use the selector :first-child
in the following manner:
$(document).ready(function(){
$("button").click(function(){
$("ul li:first-child").hide();
});
});
Both the <li>Coffee</li>
elements get hidden.
This is because the :first
selector accesses the first DOM node that satisfies the conditions given, i.e. the first element selected under the given selector.
Whereas the :first-child
selector is more specific and selects the node that is the first child of it's parent element.
As we can see, the second <li>Coffee</li>
element is the first child of the list <ul>List 2</ul>
Hence both the elements get hidden if we use the second script.
Hope this clarifies your doubts. A better practice, in my opinion, would be to use a class or id and be more specific while differentiating those elements whenever you need to.