:nth-of-type selector in jQuery
The :nth-of-type(n) selector in jQuery targets web page DOM components. CSS selectors can locate an element among siblings having the same name. It selects items differently than :nth-child(), making it useful for mixed content structures.
Making use of popular CSS selector expressions, jQuery offers a reliable and effective method for choosing items. In jQuery, the $( ) function is used to choose a portion of the document, which is the basic operation. A string, which can include any CSS selector expression, is usually passed to this function. This complete set includes the :nth-of-type selector , which makes complicated DOM traversal chores easier. Its main objective is to identify an element by its ordinal position among its exact tag name’s siblings, excluding all other instances and just counting instances of the provided tag.
Syntax:
Using the :nth-of-type(n) selector in jQuery follows the normal $(selector).action() pattern in its basic syntax. Directly given to the $ (or jQuery()) factory function is the selector string.
:nth-of-type(n)
An index (integer): Indexes are integers that represent locations based on 1. Select the third <p> element from siblings with the same name for p:nth-of-type(3). If n = 1, the first element of that type among its siblings is chosen, like first-of-type.
Keywords (even or odd):
- even: Picks even siblings when counting just elements of the defined kind. Li:nth-of-type(even) would choose all list items in their parent element that are the second, fourth, sixth, and so on by omitting non-li siblings.
- strange only covers goods that are uncomfortably placed among their siblings (first, third, fifth, etc.). All first, third, fifth, etc. list components are selected from their parent element by Li:nth-of-type(odd).
A formula (an+b): An algebraic equation can be used to create more intricate patterns of selection using the formula (an+b). An offset is denoted by b, which is 1 for beginning from the first element, and a denotes a step, such as 2 for every second element. N begins at 0. When n is 0, 1, 2, etc., li:nth-of-type(3n+1) selects the first, fourth, seventh, etc. category list items in their parent (30+1 = 1, 31+1 = 4, 3*2+1 = 7).
How it Works
Type-specific counting is the fundamental feature of :nth-of-type selector. Upon applying this selector, jQuery parses the CSS selector expression using its built-in Sizzle selector engine. Next, it finds all of a parent element’s offspring in the DOM tree, which acts as a conduit between a web page and JavaScript. It filters down to only elements with the same element name for a certain element type (such as <p> tags) and then counts the elements’ positions within that filtered set.
When invoked with a selector, the $() method returns a new jQuery object that encapsulates zero or more DOM items and allows interaction. After that, jQuery uses implicit iteration within methods to cycle throughout the selector’s items without for loops.
p:nth-child(2): For <p> elements, the selection p:nth-child(2) selects the second child of the parent. This instance’s second child of #container is <span>.S1 span</span>. Nothing would be selected by p:nth-child(2) because it isn’t a <p>. No matter the tag name, this selector counts every kid.
p:nth-of-type(2): Use this selector to find the second <p> element with the same name among siblings. Initially, all siblings in #container are detected, including those in paragraphs 1 (P1) 2, and 3 (P3). In this particular group, it qualifies. Paragraph 2 is the second <p> in this group (P2). P:nth-of-type(2) would so choose Paragraph 2 (P2).
When you only care about the location of a certain type of element or when the precise order of many element types within a parent may change, this distinction makes :nth-of-type selector more helpful. Keeping the relative order of similar components fixed ensures that your choice will resist child order changes.
This simplifies code and supports jQuery’s goal of easing web development through reusability and best practices. Sizzle prefers native DOM methods, however “loop-and-test” alternatives are used for bespoke jQuery selectors or ones lacking CSS counterparts. Selector performance is another factor to take into account. The normal CSS selector:nth-of-type selector is an exception.
Code Example
Let’s look at an example that illustrates the behaviour of :nth-of-type selector in action. A combination of span and p (paragraph) components will be used in a div element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery nth-of-type vs nth-child</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.highlight-type {
background-color: gold;
font-weight: bold;
}
.highlight-child {
background-color: skyblue;
font-style: italic;
}
</style>
</head>
<body>
<h2>:nth-of-type vs :nth-child</h2>
<div id="container">
<p>Paragraph 1</p>
<span>Span 1</span>
<p>Paragraph 2</p>
<div>Div 1</div>
<p>Paragraph 3</p>
</div>
<script>
$(document).ready(function() {
// Highlight the 2nd <p> element (of its type)
$("#container p:nth-of-type(2)").addClass("highlight-type");
// Highlight the 2nd child element (regardless of type)
$("#container :nth-child(2)").addClass("highlight-child");
});
</script>
</body>
</html>
Output:
:nth-of-type vs :nth-child
Paragraph 1
Span 1
Paragraph 2
Div 1
Paragraph 3
Explanation of the Code
HTML Structure: A variety of div, span, and p elements are present as direct children of the div with the ID content-area.
jQuery Inclusion: Add jQuery. Add a CDN’s jQuery library to the <head> <script> tag. For quicker and more dependable loading, use a CDN.
$(document).ready(): Since $(document) launches jQuery only after the HTML document loads and the DOM is ready for manipulation.Important: ready().
$(“#content-area p:nth-of-type(2)”).addClass(“highlight-type-2”);:
- This line uses the selector :nth-of-type(2).
- It specifically targets items that are p (paragraphs) (p:).
- The second <p> element is chosen within the #content-area by counting solely the paragraph elements among their siblings.
- Because it is the second <p> element in the given HTML, even if it is the third child overall (because <span>This is the first span (S1)), “This is the second paragraph (P2)” will be targeted.Before it, <span> appears.
- A gold backdrop and bold text are then set by applying the CSS class highlight-type-2 using the addClass() method.
$(“#content-area :nth-child(2)”).addClass(“highlight-child-2”);:
- The :nth-child(2) selector is used here.
- The second child element in #content-area is searched regardless of tag name.
- <span> is the HTML’s second child.This span (S1) is the first span.”</span>”
- This is followed by the addClass() method applying the highlight-child-2 CSS class, which gives it an italicised text and sky blue backdrop.
A browser will highlight “This is the second paragraph (P2)” and “This is the first span (S1)” in gold and sky blue, respectively, in this HTML file. :nth-of-type(n) may count things based purely on their element type, making it a powerful tool for picking elements in various DOM structures and increasing web development code control and readability. This visual contrast emphasises this.