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

jQuery text() method

HTML do jQuery/Métodos CSS

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 elementsto get the text content.

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

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

Atenção: 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 function 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());
});
Teste e veja‹/›

Change the text content of all paragraphs:

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

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

$("button").click(function(){
  $("p").text(function(i){
    return "O índice deste p elemento é: " + i;
  });
});
Teste e veja‹/›

Diferença entre métodos html() e text():

$("#btn1").click(function(){
  $("p").html("Eu quero dizer: <b>Hello world</b>");
});
$("#btn2").click(function(){
  $("p").text("Eu quero dizer: <b>Hello world</b>");
});
Teste e veja‹/›

Valor do Parâmetro

ParâmetroDescrição
contentDefinir a string de texto para o conteúdo de todos os elementos selecionados
Atenção:Se este parâmetro for omitido, o text() retornará o conteúdo do elemento selecionado
function(index, currentContent)Especificar uma função que retorna o conteúdo textual a ser definido
  • index-Retornar a posição do elemento na coleção

  • currentContent-Retornar o conteúdo textual atual do elemento selecionado

HTML do jQuery/Métodos CSS