jQuery document operation - 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. Specifies the function that defines 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.