jQuery first-child Selector on Multiple Lists
When applied to a class shared by multiple lists, the jQuery
:first-child selector returns the first child element of
each individual list, rather than a single element from
the entire document. This article explains how the
:first-child selector evaluates elements based on their
immediate parent hierarchy, contrasts it with jQuery's
:first selector, and provides clear examples of the
returned results.
How
:first-child Evaluates Elements
The :first-child pseudo-class is a structural selector
defined by CSS specifications and implemented within jQuery. Rather than
filtering a matched set of elements as a single flat array, it evaluates
each element's position relative to its direct parent.
If multiple lists (such as <ul> or
<ol>) share the same class name, applying a selector
targeting their children—such as
$('.my-list > li:first-child')—will cause jQuery to
inspect each list container independently. For every matching list,
jQuery identifies the element that is the first child of that parent and
adds it to the returned jQuery collection. Consequently, if there are
three lists sharing that class, the selector returns a collection
containing three elements.
Code Example
Consider the following HTML markup with two separate lists sharing
the class .menu:
<ul class="menu">
<li>Coffee</li>
<li>Tea</li>
</ul>
<ul class="menu">
<li>Bagel</li>
<li>Muffin</li>
</ul>If you execute the following jQuery code:
$('.menu li:first-child');The resulting jQuery object contains:
<li>Coffee</li>(the first child of the first.menulist)<li>Bagel</li>(the first child of the second.menulist)
Direct Application on the Class Itself
If the selector is applied directly to the class without targeting
descendants (e.g., $('.menu:first-child')), jQuery looks
for elements with the class .menu that are themselves the
first child of their own parent container. If both .menu
lists happen to be the first child of distinct parent wrappers, both
will be returned. If only one is the first child of its parent, only
that single list is returned.
Difference Between
:first-child and :first
It is common to confuse :first-child with jQuery's
proprietary :first selector:
:first-child: Returns the first child of each parent container. It can return multiple elements across a page.:first: Returns only the single, absolute first element matched in the entire DOM, ignoring parent-child boundaries.
In the previous HTML example, $('.menu li:first')
returns only <li>Coffee</li>, whereas
$('.menu li:first-child') returns both
<li>Coffee</li> and
<li>Bagel</li>.