Select Second-to-Last Child with jQuery nth-last-child
This article explains how to target and select the second-to-last
child element within a container using jQuery's
:nth-last-child() selector. You will learn the exact syntax
required, review a practical HTML and JavaScript example, and understand
the difference between this approach and related methods.
The :nth-last-child()
Syntax
The :nth-last-child(n) pseudo-class counts elements
starting from the end of the parent container toward the beginning.
Because counting starts at 1 for the very last child,
passing 2 as the argument targets the second-to-last
element.
To select the second-to-last child element within a parent container, use the following selector pattern:
$('.container :nth-last-child(2)')Alternatively, if you want to restrict the selection to direct children of a specific type (such as a list item or paragraph), target the tag directly:
$('ul > li:nth-last-child(2)')Complete Code Example
Consider an unordered list containing five items:
<ul id="my-list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li> <!-- This is the second-to-last child -->
<li>Item 5</li>
</ul>To select and apply a style to "Item 4", run:
$(document).ready(function() {
$('#my-list li:nth-last-child(2)').css('color', 'red');
});You can also use jQuery's .children() method combined
with the selector:
$('#my-list').children(':nth-last-child(2)').addClass('highlight');Key Considerations
- 1-Based Indexing: Unlike standard JavaScript arrays
which use zero-based indexing (
0, 1, 2...),:nth-last-child()uses 1-based indexing. Index1is the last child, and index2is the second-to-last child. - Sibling Types: The
:nth-last-child()selector counts all sibling elements regardless of tag name. If the second-to-last element in the container is a<div>instead of an<li>, targetingli:nth-last-child(2)will select nothing. If you have mixed tags and want the second-to-last element of a specific type, use the:nth-last-of-type(2)selector instead.