The :only-of-type Selector is used to select the elements, who are the only child of their parent of the same type.
Let us simplify with the below example.
<html> <head> <title> My First Programme </title> </head> <body> <h1> JQuery </h1> <div class = "newClass1"> <p class = "para1"> First Paragraph </p> <span class = "para2"> Second Paragraph </span> </div> <button> Click me </button> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> <script> $('button').click( function() { $('p:only-of-type').text("The content of the only child of p type got changed") }); </script> </body> </html>
So, if you see the above code. We can see that there are two elements, one of <p> type and the other of <span> type.
<div class = "newClass1"> <p class = "para1"> First Paragraph </p> <span class = "para2"> Second Paragraph </p> </div>
The corresponding DOM for it is,
And even though the <div> element has two children.
<p class = "para1"> First Paragraph </p> <span class = "para2"> Second Paragraph </p>
On button click, the contents of <p> element got changed,
And this happened with the :only-child element selector.
$('button').click( function() { $('p:only-of-type').text("The content of the only child of p type got changed") });
The moment the button is clicked, JQuery statement gets triggered.
$('p:only-of-type').text("The content of the only child of p type got changed")
And since, the <p> element is the only child of <p> type (As the other child is of <span> type).
<div class = "newClass1"> <p class = "para1"> First Paragraph </p> <span class = "para2"> Second Paragraph </p> </div>
$('p:only-of-type') changes the contents of <p> element.