jQuery :nthlastchild() Selector (original) (raw)
jQuery :nth-last-child() Selector
Last Updated : 11 Jul, 2025
The jQuery :nth-last-child() selector is used to select all elements that are the nth last child of their parent. The counting of elements starts from the last element.
Syntax:
:nth-last-child( n | even | odd | formula )
Parameters: The :nth-last-child() selector contain parameters which are listed below:
- n: It holds the child index number of the selected elements. The counting starts from the end. The index number of the first child is 1.
- even: It selects all even child elements.
- odd: It selects all odd child elements.
- formula: It is used to specify the formula to select the child element. The formula can be in form of (an + b).
Below examples illustrate the :nth-last-child() selector in jQuery:
Example 1: This example changes the background color to green and text color to the white of the second last heading of their parents (div tags).
HTML `
jQuery :nth-last-child() Selector<!-- Script to use nth-last-child selector -->
<script>
$(document).ready(function () {
$("h4:nth-last-child(2)").css({
"background-color": "green",
"color": "white"
});
});
</script>
<style>
option {
font-weight: bold;
font-size: 25px;
color: green;
}
select {
font-weight: bold;
font-size: 25px;
color: green;
}
</style>
jQuery | :nth-last-child() Selector
The first heading in first div.
The second last heading in first div.
The last heading in first div.
The first heading in second div.
The second last heading in first div.
The last heading in second div.
`
Output:
Example 2: This example changes the background color to green and the text color to white of the second last heading of the tag.
HTML `
jQuery :nth-last-child() Selector<!-- Script to use nth-last-child selector -->
<script>
$(document).ready(function () {
$("h4:nth-last-child(3)").css({
"background-color": "green",
"color": "white"
});
});
</script>
<style>
option {
font-weight: bold;
font-size: 25px;
color: green;
}
select {
font-weight: bold;
font-size: 25px;
color: green;
}
</style>
jQuery | :nth-last-child() Selector
The first heading in first div.
The second last heading in first div.
The last heading in first div.
The first heading in second div.
The second last heading in first div.
The last heading in second div.
`
Output:
