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




HTML METHODS - text()


The text() method is used to get and set content of an HTML element.


text() as Getter method


Example :



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

  	<body>
    	<h1> JQuery </h1>
    	<p> New Code </p>

      	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
	  
      	<script>
      
			var x = $('p').text();
			document.write("The content of p tag is ::", x)
            
      	</script>      
   </body>
</html>


Output :




Now, we just need to look at the JQuery code. So, let us take the JQuery code chunk and analyse it,


var x = $('p').text();
document.write("The content of p tag is ::", x)

And we need to do is, access the text inside the <p> element.


<p> New Code </p>

So, we have used a text() method along with the selector, so that we can get the actual text i.e. New Code.


var x = $('p').text();

And after we got the text i.e. New Code. We assign it to a variable x.

JQuery HTML Methods text()

And we print the value of x using document.write() statement.


In brief, html body p is the Selector. And we pass html body p to JQuery to get the text using the text() Method.


So, text() method can be said as a Getter method because it gets the content of the <p> element.

JQuery HTML Methods text()

text() as Setter method


Example :



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

  	<body>
    	<h1> JQuery </h1>
    	<p> New Code </p>
    	
    	<button> Click to set a new value </button>
    	

      	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
	  
      	<script>
      
      		$('button').click( function() {
				$('p').text("The content is changed");
			});
			
            
      	</script>      
   </body>
</html>


Output :




So, in the above code, we have to change the text inside the <p> element.


<p> New Code </p>

And we have done it using the JQuery statement,


$('button').click( function() {
	$('p').text("The content is changed");
});

So, on button click, the text() function is called,


$('p').text("The content is changed");

And the content of <p> element gets replaced with, The content is changed.


This is because the text() function is used to set a new value to the <p> element.