i am having a ul li list
<ul>
<li>Parent
<ul>
<li>
child1
</li>
<li>
child2
</li>
</ul>
</li>
</ul>
and i am trying to use a selector jQuery('ul li:first')
and jQuery('ul li:first-child')
both giving the same result this makes me confused about the difference between the two is there a example which clarifies the difference between two selectors
From Official Docs:
While
:first
matches only a single element, the:first-child
selector can match more than one: one for each parent. This is equivalent to:nth-child(1)
.http://api.jquery.com/first-selector/
Update:
Here is an example using
:first-child
:http://jsbin.com/olugu
You can view its soruce and edit yourself. If you replace
:first-child
with:first
, it will only highlight the first word there. This is what is defined for them.And here is example using
:first
:http://jsbin.com/olugu/2
From your example:
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>
.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:
the query below will yield 0 results as
<span>
is not the first-child of div.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.This is an illustration of what
$("prev next:first")
and$("prev next:first-child")
would actually select::first
returns only the first result, while:first-child
returns one result per parent (if any).Sometimes, but not always, the result is (and should) be the same.
Given your HTML:
So, you can see, that the first line is returning only the first
li
element.The second line is returning both
li
elements that are afirst-child
of their parent.:first
returns the first in a matched set.:first-child
returns elements that are the first child element of their parent.The first
li
element in your HTML is also a first child, although using:first-child
is yielding more results when you test thelength
property.You could actually combine the two selectors if you only want the first match that is a first child.
when we use
:first
it selects the first child element of the first specified element and when we use:first-child
it select all first child element of the specified element.