• jQuery Video Tutorials

jQuery :odd Selector



The :odd selector in jQuery is used to select elements with an odd index within a set of matched elements. The indexing is zero-based, meaning the first element has an index of 0, the second an index of 1, and so on.

Note: If we want to select the elements with even index numbers, we need to use the :even selector.

Syntax

Following is the syntax for jQuery :odd selector −

$("selector:odd")

Parameters

Following is the explantion of above syntax −

  • selector: This is a CSS selector. It specifies the criteria for selecting elements. For example:
  • "div" selects all <div> elements.

  • ".class" selects all elements with the class "class".

  • "#id" selects the element with the id "id".

  • odd: Filters the matched set to include only elements with an odd index.

Example 1

In the following example, we are demonstrating the basic usage of the jQuery :odd selector −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        $("button").click(function(){
            $("li:odd").css("background-color", "grey");
        })
    });
</script>
</head>
<body>
<ul>
  <li>Even (index: 0)</li>
  <li>Odd (index: 1)</li>
  <li>Even (index: 2)</li>
  <li>Odd (index: 3)</li>
  <li>Even (index: 4)</li>
</ul>
<button>Click</button>
</body>
</html>

After clicking the button, the :odd selector will select all the odd-indexed list elements and highlight them with a grey background color.

Example 2

In this example below, we are hiding the odd-indexed <div> elements using the ":odd" selector −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
      $("button").click(function(){
        $("div:odd").hide();
      })
    });
  </script>
</head>
<body>
<div>Even Div (Index: 0)</div>
<div>Odd Div (Index: 1)</div>
<div>Even Div (Index: 2)</div>
<div>Odd Div (Index: 3)</div>
<div>Even Div (Index: 4)</div>
<button>Click</button>
</body>
</html>

When we click the button, all the odd-indexed div elements will be hidden.

jquery_ref_selectors.htm
Advertisements