The ':parent Selector' is used to select the elements, those are the parents of some text or other element.
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> </div> <div class = "newClass2"> <p class = "newPara"></p> </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:parent').text("p is a parent and got replaced") }); </script> </body> </html>
So, if you see the above code. We can see that there are two <div> elements, and both has a <p> element in it.
<div class = "newClass1"> <p class = "para1"> First Paragraph </p> </div> <div class = "newClass2"> <p class = "para2"></p> </div>
And the <p> element of the second <div> has nothing inside it.
<p class = "para2"></p>
Now, we want to change the contents of the <p> element that is a parent.
And if we see the above code,
<p class = "para1"> First Paragraph </p>
<p> element is the parent of the text 'First Paragraph'.
And since,
<p class = "para2"></p>
The contents of <p> element is empty, it is not the parent of any text. In other words it is not a parent.
And we only want to change the contents of the <p> element that is a parent.
And this happened with the 'p:parent' element selector.
$('button').click( function() { $('p:parent').text("p is a parent and got replaced") });
The moment the button is clicked, JQuery statement gets triggered.
$('p:parent').text("p is a parent and got replaced")
And the JQuery code locates the <p> element that is the parent and changes its contents.
Similarly, in the next example, we will be checking if a <div> element is a parent and change its contents.
<html> <head> <title> My First Programme </title> </head> <body> <h1> JQuery </h1> <div class = "newClass1"> <p class = "para1"> First Paragraph </p> </div> <div class = "newClass2"> <p class = "newPara"></p> </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() { $('div:parent').text("div is a parent and got replaced") }); </script> </body> </html>
Now, we are checking if <div> is a parent or not and change its contents accordingly.
$('button').click( function() { $('div:parent').text("div is a parent and got replaced") });
And We can see that there are two <div> elements, and both has a <p> element in it.
<div class = "newClass1"> <p class = "para1"> First Paragraph </p> </div> <div class = "newClass2"> <p class = "para2"></p> </div>
So, the contents of both the <div> elements gets changed.