Home »
jQuery »
jQuery Selectors
jQuery :nth-last-of-type Selector
jQuery | :nth-last-of-type Selector: Learn about the jQuery :nth-last-of-type Selector with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on November 05, 2022
:nth-last-of-type Selector
In jQuery, selectors are a parameter through which we can select the HTML element. Selectors can comprise – class names, ids, tag names, attributes, etc. Basically, by using selectors, the appropriate HTML-DOM element can be selected and hence performed actions on it. Here, we are discussing the jQuery :nth-last-of-type Selector.
The jQuery :nth-last-of-type selector helps to select the nth child occurrence of the specified tag (particular tag) from the last within their parent elements. It is used along with some tag names prepended to it. If 'div' is specified then, it will return those divs which are at the nth child number to their parent element from last. It can return more than one element.
:nth-last-of-type Selector Syntax
$('elementName:nth-last-of-type(n/even/odd/formula)');
It takes a few parameters: n, even, odd, formula.
- n: is the index of the child element that you want to select from last.
- even: the keyword 'even' can be passed to get the child elements at the even index position from last.
- odd: the keyword 'odd' can be passed to get the child elements at the odd index position from last.
- formula: Any specific formula or equation can be passed to get that particular indexed element from the last.
Once the elements are selected, you can access them and perform the actions that you want to perform on them. The example given below shows the selection of the nth child element from the last of type 'div' on click by passing the appropriate selector.
jQuery :nth-last-of-type Selector Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h2>jQuery - Nth-last-of-type Selector</h2>
<p>Click the button and get the nth-last-of-type selector of the selected element.</p>
<button>Nth-last-of-type Selector</button>
<hr>
<div>
<p>One</p>
<p>Two</p>
<div>Div One</div>
<p>Three</p>
<div>Div Two</div>
<p>Four</p>
</div>
<hr>
<div>
<p>One</p>
<p>Two</p>
<p>Three</p>
<div>Div One</div>
<p>Four</p>
</div>
<hr>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('button').click(function(){
$('p:nth-last-of-type(3)').css({'color':'red', 'font-size':'larger'});
});
});
</script>
</html>
Output: