:Odd Selector in jQuery
To choose particular HTML components based on where they are in a matched collection, jQuery’s :odd selector is a useful tool. In order to increase readability, it is especially helpful when applying styles or behaviours to alternating elements, such “striping” rows in a table.
What is the selector?
The jQuery :odd selector filters. It chooses entries with odd index values (0-based) in its set. These elements will be selected if you provide a list of elements. It complements the :even filter, which picks even-indexed elements (0, 2, 4, etc.).
Syntax:
jQuery’s standard $(selector).action() pattern is followed in the basic syntax for utilising the :odd selector. The first set of elements you wish to filter is defined by another selection that you append :odd to.
$(selector).action()
For example:
- From the second list item (index 1), $(‘li:odd’) will choose every other item.
- The function $(‘tr:odd’) will choose every other table row.
How it Works
The “fast and concise JavaScript Library,” jQuery, makes standard web development tasks like event handling and HTML page traversing easier. The odd selector exemplifies this simplification by offering a simple method of targeting components according to their sequential location without the need for intricate human reasoning.
Zero-Based Indexing: Understanding that jQuery’s :odd and :even selectors employ zero-based indexing is essential. In other words, index 0 is the initial element in any collection.
- The value of index 0 is even.
- An odd number is index one.
- The value of index 2 is even.
- An odd number is index three.
By using :odd, you are choosing the second, fourth, sixth, and so forth elements in the matched set. It might occasionally be counterintuitive to think in terms of “first, second, third” in natural language.
Implicit Iteration: The use of implicit iteration is one of the main benefits of jQuery. You can avoid writing an explicit for loop to iterate over each selected element by using a jQuery method, such as.addClass(), on a selection obtained with :odd. For each element in the set that matches the selection, jQuery automatically acts. You write less code than using regular JavaScript.
Simplification and Cross-Browser Compatibility: Using styles in plain JavaScript and manually identifying components based on their index can be time-consuming and vulnerable to browser variations. jQuery abstracts these intricacies away. Its selector engine, Sizzle, is made to function consistently across a range of web browsers by finding components quickly and reliably. Developers may concentrate on the intended result instead of the underlying browser oddities with the :odd selector, which is a component of this reliable approach.
Practical Applications:Commonly referred to as “row striping,” the main application for filters such as :odd and :even is to style items in an alternating pattern.Odd-indexed rows should be coloured differently than even-indexed rows to make a table easier to read. One line of jQuery code does this.
Code Example
Here is a brief program that illustrates the odd selector. When a button is hit, JavaScript (jQuery) code highlights odd-indexed list items in this HTML structure.
<!DOCTYPE html>
<html>
<head>
<title>:odd Selector Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
ul {
list-style: none;
padding: 0;
max-width: 300px;
margin: 20px auto;
font-family: sans-serif;
}
li {
padding: 10px;
background: #f0f0f0;
border-bottom: 1px solid #ccc;
}
li.highlight {
background-color: #cce5ff;
font-weight: bold;
color: #004085;
}
button {
margin: 10px;
padding: 8px 15px;
font-size: 14px;
cursor: pointer;
}
</style>
</head>
<body>
<ul id="myList">
<li>Item 1 (index 0)</li>
<li>Item 2 (index 1)</li>
<li>Item 3 (index 2)</li>
<li>Item 4 (index 3)</li>
<li>Item 5 (index 4)</li>
</ul>
<div style="text-align:center;">
<button id="highlightBtn">Highlight :odd</button>
<button id="resetBtn">Reset</button>
</div>
<script>
$(document).ready(function() {
$("#highlightBtn").click(function() {
$("#myList li:odd").addClass("highlight");
});
$("#resetBtn").click(function() {
$("#myList li").removeClass("highlight");
});
});
</script>
</body>
</html>
Output:
Item 1 (index 0)
Item 2 (index 1)
Item 3 (index 2)
Item 4 (index 3)
Item 5 (index 4)
Highlight :odd Reset
How the Program Works
HTML Structure: The HTML structure includes an unordered list (<ul>) with ten items (<li>). Natural number, 0-based index, and parity (Even/Odd) are clearly labelled for each list item.
jQuery Inclusion: The script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js”>/script> line incorporates the CDN-provided jQuery library. For faster loading and reliability, use a CDN.
$(document).ready():Wrap the jQuery code in $(document).ready(function(){…});. This ensures that the code runs only after the HTML document is entirely loaded and the DOM is properly created and ready for manipulation. This avoids script issues when accessing unrendered components.
Applying the Highlight:
- To apply the highlight, click the “Apply :odd Highlight” button and execute the jQuery selector $(“#myList li:odd”).
- To select all <li> components that are descendants of the <ul> with the ID myList, use $(“#myList li”). It creates 10 list items.
- To filter the set, use :odd to keep only <li> elements with odd 0-based indexes. They are ranked 2nd, 4th, 6th, 8th, and 10th.
- Finally, apply the CSS class “highlight-odd” to the filtered items using.addClass(“highlight-odd”). These list items are visually styled by highlight-odd CSS (light blue background, bold text, blue left border).
Resetting Styles: $(“#myList li”) is used by the “Reset Styles” button.Remove the class “highlight-odd” from all list items to restore their default appearance.
This little program shows how the :odd selector and other jQuery methods may accurately target and change web page components with minimal and legible code.