The jQuery text() method can be used to return or set the text content for the selected element. It overwrites the text content of the selected element when specified. You can change the text content using this method.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of these parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify the element to select and add text content to it. Use tag name, class name, or id of the elements to select. It is a required field. |
content | Specify the text content to set for the selected element. It is a required field. |
index | It returns the index position of the element. |
current_content | Return the current content of the element. |
jQuery text() Method to Get Text Content
If you want to get or return the text content of the selected element, you have to use the method as given below. Use the method without specifying any parameter. The example store the content of the selected element in a variable.
Example
1 2 3 4 5 6 7 8 9 10 |
<script> $(document).ready(function(){ $('.mygetbtn').click(function(){ var mypara = $("p").text(); alert(mypara); }); }); </script> <p>This is my paragraph.</p><br> <button type="button" class="mygetbtn">Click to Get Text Content</button> |
Output
This is my paragraph.
When you click the button given above, it displays the alert box containing the text content of the selected element.
Set Text Content Using the Method
If you want to set the text content of the selected element, you have to use the method as given below. You have to specify the text content as the parameter of the jQuery text() method. The method overwrites the text content of the selected element with the specified one.
Example
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $('.mysetbtn').click(function(){ $("p").text("Learn jQuery from TutorialDeep."); }); }); </script> <p>This is my paragraph.</p><br> <button type="button" class="mysetbtn">Click to Set Text Content</button> |
Output
This is my paragraph.
Click the button given above to set the content of the selected element. You will get the specified content replaces with the old content.
Use Function to Set the Text Content
You can also set the text content using the function with the jQuery text() method. Use the method as given in the example below.
Example
1 2 3 4 5 6 7 8 9 10 11 |
<script> $(document).ready(function(){ $('.mysetfnbtn').click(function(){ $("p").text(function(){ return "Learn with jQuery live examples."; }); }); }); </script> <p>This is my paragraph.</p><br> <button type="button" class="mysetfnbtn">Click to Set Text Content</button> |
Output
This is my paragraph.
When you click the button given above, the method sets the specified text content and overwrites the old content.
You may also like to read
I hope you like this tutorial on jQuery text() method. If you have any queries regarding the tutorial, please comment below.
References