Cover Image for jQuery odd() method
90 views

jQuery odd() method

As of my last update in September 2021, the jQuery.odd() method is not a part of the core jQuery library. There is no official odd() method in jQuery.

However, jQuery provides various filter methods, and one of them is the :odd selector, which can be used to select odd-indexed elements in a collection of elements.

Here’s the basic syntax of the :odd selector:

$("selector:odd")

In this syntax, "selector" is a valid jQuery selector that selects a collection of elements, and :odd filters the collection to only select odd-indexed elements.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery :odd Selector Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        li {
            list-style: none;
        }

        li:nth-child(odd) {
            background-color: #f2f2f2; /* Applying background color to odd-indexed li elements */
        }
    </style>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
    </ul>

    <script>
        $(document).ready(function() {
            // Select all odd-indexed li elements and apply background color to them
            $("li:odd").css("font-weight", "bold");
        });
    </script>
</body>
</html>

In this example, we have an unordered list with several <li> elements. We use the :odd selector to select all odd-indexed <li> elements and apply bold font weight to them.

Keep in mind that :odd uses a zero-based index, meaning the first element in the collection has index 0, the second has index 1, and so on. So, :odd selects elements with index 1, 3, 5, and so on.

As a side note, while there is no official jQuery.odd() method, you can easily achieve similar functionality using the :odd selector in jQuery’s filter methods.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS