The text() method is used to get and set content of an HTML element.
<html>
<head>
<title> My First Programme </title>
</head>
<body>
<h1> JQuery </h1>
<p> New Code </p>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"> </script>
<script>
var x = $('p').text();
document.write("The content of p tag is ::", x)
</script>
</body>
</html>
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.
1.png)
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.
2.png)
<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://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"> </script>
<script>
$('button').click( function() {
$('p').text("The content is changed");
});
</script>
</body>
</html>
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.