2 of 119 menu

The text method

The text method allows you to get the text of elements, including their descendants, and change it.

Syntax

Getting text:

$(selector).text();

Change text:

$(selector).text(new text);

Replaces the contents of the selected elements with the value returned by the custom function. The function is called separately, for each of the selected elements. When called, it is passed the following parameters: index — position of element in set, value — current text content:

$(selector).text(function(number in set, current element content));

Example

Let's display the contents of our paragraph:

<p id="test">text</p> let text = $('#test').text(); alert(text);

See also

  • method html,
    which allows you to get the text of an element along with tags
  • JavaScript property outerHTML,
    with which you can change the text of an element along with its tag in pure JavaScript
  • JavaScript property innerHTML,
    with which you can change the text of an element in pure JavaScript
enru