The jQuery :nth-last-of-type() Selector is used to select all child of a parent with the same element name, counting from the last to first. It uses 1-indexed counting.
Syntax:
element:nth-last-of-type(n|even|odd|formula)
Parameters:
- n: It selects nth element from last.
- even: It selects every even element from last.
- odd: It selects every odd element from last.
- formula: It holds the formula to generate grouping of elements, starting from the last, For example, 3n+2 selects every element which is the output of this expression by taking values of n-0, 1, 2, …
Example 1: This example use :nth-last-of-type() selector to select odd element from the last.
HTML
<!DOCTYPE html>
< html >
< head >
< title >
jQuery | :nth-last-of-type() Selector
</ title >
< script src =
</ script >
</ head >
< body >
Computer Science Subjects
< ul >
< li >Data Structure</ li >
< li >Algorithm Analysis</ li >
< li >Operating System</ li >
< li >Computer Networks</ li >
< li >Web Technology</ li >
< li >C Programming</ li >
< li >C++ Programming</ li >
< li >Java</ li >
</ ul >
< script >
$(document).ready(function () {
let el = $("ul li:nth-last-of-type(odd)").css({
background: "green"
});
});
</ script >
</ body >
</ html >
|
Output:
Example 2: This example use :nth-last-of-type() selector to select last element.
HTML
<!DOCTYPE html>
< html >
< head >
< title >
jQuery | :nth-last-of-type() Selector
</ title >
< script src =
</ script >
</ head >
< body >
< section >
< article >
< p >Company - GeeksforGeeks</ p >
< p >Name - ABC</ p >
< p >Email - abc@geeksforgeeks.org</ p >
</ article >
< article >
< p >Company - GFG</ p >
< p >Name - XYZ</ p >
< p >Email - xyz@gfg.org</ p >
</ article >
< article >
< p >Company - G4G</ p >
< p >Name - Geeks</ p >
< p >Email - geeks@g4g.org</ p >
</ article >
</ section >
< script >
$(document).ready(function () {
$("article p:first-of-type").css({
fontWeight: "bold",
fontSize: '1.2rem'
})
$("article p:nth-last-of-type(1)").css({
fontStyle: 'italic',
opacity: 0.8
})
})
</ script >
</ body >
</ html >
|
Output:
