Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




SELECTORS - :only-child Selector


The :only-child Selector is used to select the elements, who are the only child of their parent.


Let us simplify with the below example.


Example :



<html>
  	<head>
    	<title> My First Programme </title>
  	</head>

  	<body>
    	<h1> JQuery </h1>
    	
    	<div class = "newClass1">
    		<p class = "para1"> First Paragraph </p>
    		<p class = "para2"> Second Paragraph </p>
    		<p class = "para3"> Third Paragraph </p>
    	</div>
    	
    	<div class = "newClass2">
    		<p class = "newPara"> Next Paragraph </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:only-child').text("The content of the only child got changed")
            });
            
      	</script>      
  	</body>
</html>


Output :



So, if you see the above code. We can see that there are three <p> elements, those are inside a <div> element.


<div class = "newClass1">
	<p class = "para1"> First Paragraph </p>
	<p class = "para2"> Second Paragraph </p>
	<p class = "para3"> Third Paragraph </p>
</div>

The corresponding DOM for it is,

java_Collections

Also there is another <div> element that has one child,


<div class = "newClass2">
	<p class = "newPara"> Next Paragraph </p>
</div>

The DOM for it is,

java_Collections

The <div> element has three children of type <p>.


<p class = "para1"> First Paragraph </p>
<p class = "para2"> Second Paragraph </p>
<p class = "para3"> Third Paragraph </p>

And the third child of <div> element is,


<p class = "newPara"> Next Paragraph </p>

And on button click, the contents of the <div> element with only child,


<div class = "newClass2">
	<p class = "newPara"> Next Paragraph </p>
</div>

Gets changed to The content of the only child got changed.


And this happened with the :only-child element selector.


$('button').click( function() {
	$('p:only-child').text("The content of the only child got changed")
});

The moment the button is clicked, JQuery statement gets triggered.


$('p:only-child').text("The content of the only child got changed")

And the JQuery code locates the <p> element that is the only and changes its contents.