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




SELECTORS - First Element Selector


The First Element Selector is used to select the first occurence of a particular element.


Let us simplify with the below example.


Example :



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

  	<body>
    	<h1> JQuery </h1>
    	<p class = "para1"> First Paragraph </p>
    	<p class = "para2"> Second Paragraph </p>
    	<p class = "para3"> Third Paragraph </p>
    	
    	<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:first').text("The first occurance of p element got replaced")
            });
            
      	</script>      
  	</body>
</html> 


Output :



So, if you see the above code. We can see that there are three <p> elements,


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

And the first occurence of <p> element is,


<p class = "para1"> First Paragraph </p>

And on button click, the contents of first element gets replaced with The first occurance of p element got replaced.


And this happened with the :first element selector.


$('button').click( function() {
	$('p:first').text("The first occurance of p element got replaced")
});

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


$('p:first').text("The first occurance of p element got replaced")

And the JQuery code locates the first occurence of <p> element and changes its contents.