Open In App

jQuery :only-of-type Selector

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The :only-of-type Selector is an inbuilt selector in jQuery, used to select all the elements that are the only child of their parent. 

Syntax:

$("parent_name : only-of-type")

Example 1: In this example, we are using only-of-type selectors.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
    <!-- Script to use only-of-type selector -->
    <script>
        $(document).ready(function () {
            $("p:only-of-type").css(
                "color", "green");
        });
    </script>
</head>
 
<body>
    <center>
        <!-- Division 1 -->
        <div style="border:1px solid;">
            <p>Geek1 of first div.</p>
            <p>Geek2 of first div.</p>
        </div>
        <br>
        <!-- Division 2 -->
        <div style="border:1px solid;">
            <p>The only Geek of second div.</p>
        </div>
        <br>
        <!-- Division 3 -->
        <div style="border:1px solid;">
            <span>GeeksforGeeks</span>
            <p>The only Geek of third div.</p>
        </div>
    </center>
</body>
 
</html>


Output:

  

In the above example, all the only child element( here p tags ) of their parent( here div tags ) are formatted into green color i.e, “The only Geek of the second div.” and “The only Geek of the third div.”. 

Example 2: 

html




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
    <!-- Script to use only-of-type selector -->
    <script>
        $(document).ready(function () {
            $("p:only-of-type").css(
                "color", "green");
        });
    </script>
</head>
 
<body>
    <center>
        <!-- Children of division -->
        <h3>Division as a parent</h3>
        <div>
            <p>Geek1 of div.</p>
            <p>Geek2 of div.</p>
        </div>
        <!-- Only child of id -->
        <h3>ID as a parent.</h3>
        <id>
            <p>The only Geek of id.</p>
        </id>
        <!-- Only child of class -->
        <h3>Class as a parent.</h3>
        <class>
            <p>The only Geek of class.</p>
        </class>
        <!-- Only child of body -->
        <h3>Body as a parent.</h3>
        <p>The only Geek of body.</p>
    </center>
</body>
 
</html>


Output:

  

In the above example, all the only child element( here p tags ) of their respective parent are formatted into green color i.e, “The only Geek of id.”, “The only Geek of class.” and “The only Geek of the body.” as every paragraph tag is considered the different child for each parent.



Last Updated : 06 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads