jQuery Document Manipulation - text() Method

Example

Set the content of all <p> elements:

$(".btn1").click(function(){
  $("p").text("Hello <b>world</b>!");
});

Try It Yourself

Definition and Usage

The text() method sets or returns the text content of the selected elements.

Return Text Content

When this method is used to return a value, it will return the combined text content of all matching elements (HTML tags will be removed).

Syntax

$(selector).text()

Try It Yourself

Set Text Content

When this method is used to set a value, it will overwrite all content of the selected elements.

$(selector).text(content)

Try It Yourself

Parameters Description
content Specifies the new text content of the selected elements. Note: Special characters will be encoded.

Use the function to set text content

Use the function to set the text content of all selected elements.

Syntax

$(selector).text(function(index, oldcontent))

Try It Yourself

Parameters Description
function(index, oldcontent)

Required. Defines the function that specifies the new text content of the selected elements.

  • index - Optional. Accepts the index position of the selector.
  • html - Optional. Accepts the current content of the selector.