jQuery text() Method

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.

jQuery text() Method

Syntax

The syntax of this method is given below:-

Syntax
$(selector).text()
Syntax
$(selector).text(content)
Syntax
$(selector).text(function(index, current_content))

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

Test it Live

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

Test it Live

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

Test it Live

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