English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery text() method

jQuery HTML/CSS Methods

The text() method gets or sets the text content of the selected element (including its descendants).

When using the text() methodGetcontent, it will returnAll selected elementsof the text content.

When using the text() methodSetWhen setting content, it will overrideAll selected elementsof the text content.

Usehtml()method to get or set the innerHTML (text+ HTML tags).

Note: The text() method cannot be used on input elements. For input field text, please useval()Method.

Syntax:

Get text content:

$(selector).text()

Set text content:

$(selector).text(content)

Use the feature to set text content:

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

Example

Click the button to get the text content of all paragraphs:

$("button").click(function() {
  alert($("p").text());
});
Test and see‹/›

Change the text content of all paragraphs:

$("button").click(function() {
  $("p").text("I would like to say: Hello world");
});
Test and see‹/›

Use the following function to change the text content of an element:

$("button").click(function() {
  $("p").text(function(i){
    return  "The index of this p element:  " + i;
  });
});
Test and see‹/›

The difference between html() method and text() method:

$("#btn1").click(function(){
  $("p").html("I want to say:  <b>Hello world</b>
});
$("#btn2").click(function(){
  $("p").text("I want to say:  <b>Hello world</b>
});
Test and see‹/›

Parameter Value

ParameterDescription
contentSet the text string for the content of all selected elements
Note:If this parameter is omitted, text() will return the content of the selected element
function(index, currentContent)Specify a function that returns the text content to be set
  • index-Return the index position of the element in the collection

  • currentContent-Return the current text content of the selected element

jQuery HTML/CSS Methods