• jQuery Video Tutorials

jQuery :only-child Selector



The :only-child selector in jQuery is used to select elements that are the only child of their parent. In other words, It targets elements that have no siblings within the same parent element.

Syntax

Following is the syntax of jQuery :only-child Selector −

$(":only-child")

Parameters

This selector will filter and select elements that are the only child of its parent.

Example 1

In the following example, we are using the jQuery :only-child Selector to select each <p> element that is only child of its parent <div> −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:only-child").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div style="border: 1px solid black;">
        <p>Only paragraph</p>
    </div><br>
    <div style="border: 1px solid black;">
        <p>First paragraph</p>
        <p>Second paragraph</p>
    </div><br>
    <div style="border: 1px solid black;">
        <p>Only paragraph</p>
    </div>
</body>
</html>

After executing the above program, the selected elements will be highlighted with yellow background color.

Example 2

Here, we are selecting each <span> element that is only child of its parent (<div>) −

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Add a class to the only child of each parent div
            $("div span:only-child").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div style="border: 1px solid black;">
        <span>Only span</span>
    </div><br>
    <div style="border: 1px solid black;">
        <span>First span</span>
        <span>Second span</span>
    </div><br>
    <div style="border: 1px solid black;">
        <span>Another span</span>
        <span>And another one</span>
    </div>
</body>
</html>

After executing, the selected elements will be highlighted with yellow background color.

jquery_ref_selectors.htm
Advertisements