🚨 Time is Running Out: Reserve Your Spot in the Lucky Draw & Claim Rewards! START NOW

Code has been added to clipboard!

jQuery .text(): Get or Set Text for HTML Elements

Reading time 1 min
Published Jan 24, 2018
Updated Sep 27, 2019

jQuery text: Main Tips

  • jQuery .text() returns the text inside the selected elements and their descendants.
  • You can also make jQuery change text inside each matched element to the specified content.
  • Text is always defined in a string.

Using .text()

The .text() method sets or returns the text inside the specified elements. Differently from .html(), jQuery .text() is applicable to both XML and HTML documents.

In the example below, the function sets text to a <h1> element:

Example
$("button").click(() => {
    $("h1").text("Hello world!");
});

When no parameters are defined, .text() jQuery retrieves the text inside elements:

$(selector).text();

Follow this syntax to jQuery change text:

$(selector).text(content);

To make jQuery set text, a function can also be added to retun the text needed:

$(selector).text(function);

In this case, the function receives these arguments:

  • index - the index of the currently selected element in the set of matched elements.
  • currentContent - the original text value of elements.

Tip: do not apply .text jQuery to form inputs or scripts. Use .val() instead.