Skip to content
Related Articles

Related Articles

Improve Article
jQuery | :only-of-type Selector
  • Difficulty Level : Hard
  • Last Updated : 01 Mar, 2019

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:




<!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:




<!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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :