jQuery Selector for First Child of Every List
This article explains how to select the first child of every list on
a webpage using jQuery. It covers the exact selector syntax required,
explains the critical difference between the :first and
:first-child selectors, and provides clear code examples to
help you style or manipulate these elements effectively.
To select the first item of every list (<ul> or
<ol>), use the :first-child pseudo-class
selector.
The Selector Syntax
$('li:first-child')If you want to be more explicit and target only unordered and ordered lists, you can write:
$('ul > li:first-child, ol > li:first-child')Why Use
:first-child Instead of :first?
A common mistake in jQuery is using the :first
selector:
// Incorrect: Only selects the first <li> on the entire page
$('li:first') :firstis a jQuery-specific filter that returns only one element: the absolute first match in the entire document.:first-childis a native CSS pseudo-class implemented in jQuery that checks the relationship of each element to its parent. It matches every<li>that is the first child of its respective parent list.
Practical Example
Given the following HTML structure:
<ul id="list-one">
<li>Item 1A</li>
<li>Item 1B</li>
</ul>
<ul id="list-two">
<li>Item 2A</li>
<li>Item 2B</li>
</ul>You can target both "Item 1A" and "Item 2A" at the same time using:
$(document).ready(function() {
$('li:first-child').css('font-weight', 'bold');
});This applies bold styling to the first item of every list on the page without affecting the subsequent items.