• jQuery Video Tutorials

jQuery parent > child Selector



The parent > child selector in jQuery is used to select direct child elements that are nested within a parent element.

Syntax

Following is the syntax of jQuery parent > child Selector −

("parent > child")

Parameters

Here is the description of the above syntax −

  • parent: Specifies the parent element.
  • child: Specifies the direct child element within the parent.

Example 1

In the following example, we are using the "jQuery parent > child Selector" to select the direct child paragraphs of <div> element −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        div {
            padding: 10px;
            border: 1px solid black;
        }
        p {
            margin: 5px;
            padding: 5px;
            border: 1px solid blue;
        }
    </style>
    <script>
        $(document).ready(function(){
            // Select and apply styles to direct child paragraphs of div
            $("div > p").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div>
        <p>First paragraph (direct child)</p>
        <span><p>Child paragraph within span (not direct child)</p></span>
        <p>Second paragraph (direct child)</p>
    </div>
</body>
</html>

After executing the above program, the direct child paragraphs of <div> element will be highlighted with yellow background color.

Example 2

In this example, we are selecting the direct child lists items of <ul> −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        ul {
            padding: 10px;
            border: 1px solid black;
        }
        li {
            margin: 5px;
            padding: 5px;
            border: 1px solid green;
        }
    </style>
    <script>
        $(document).ready(function(){
            // Select and apply styles to direct child list items of ul
            $("ul > li").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <ul>
        <li>First item (direct child)</li>
        <li>Second item (direct child)</li>
    </ul>
</body>
</html>

After executing, the direct child lists items of <div> element will be highlighted with yellow background color.

jquery_ref_selectors.htm
Advertisements