Open In App

How to apply CSS in odd childs of parent node using jQuery ?

Last Updated : 09 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to set styles in the odd child of the parent element using jQuery. To set the style on the odd child of the parent, we use jQuery :nth-child(odd) selector.

The :nth-child(odd) selector is used to select every element that is the odd child of its parent element.

Syntax:

$("Selector:nth-child(odd)")

Approach: First, we create an HTML element containing a div element. This div element contains some paragraph element, then we use :nth-child() selector to select all odd-position children of the parent element.

Example: In this example, we will use the above approach.

HTML




<!DOCTYPE html>
<html>
<head>
    <script src=
    </script>
    <style>
        div {
            font-size: 18px;
            font-weight: bold;
        }
        p {
            margin-left: 50px;
        }
    </style>
    <script>
        $(document).ready(function () {
            $("p:nth-child(odd)").css({
                backgroundColor: "green",
                color: "white",
                padding: "5px 15px",
                display: "table"
            });
        });
    </script>
</head>
<body>
    <h1 style="color: green;">GeeksforGeeks</h1>
    <h3>
        How to apply CSS in odd childs of parent
        node using jQuery library?
    </h3>
    <div>
        <p>Data Structure</p>
        <p>C++ Programming</p>
        <p>javaScript</p>
        <p>Web Technology</p>
    </div>
</body>
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads