How to Set Text Content in jQuery

Setting the text content of an element in jQuery is a fundamental DOM manipulation task that allows developers to dynamically update what users see on a webpage. This guide covers how to use the .text() method to replace or set plain text within selected HTML elements, demonstrates practical examples, and highlights the difference between updating text and inserting HTML markup.

Using the .text() Method

The primary and most efficient way to set the text content of an element in jQuery is by using the .text() method. When passed a string argument, this method replaces the existing content of the selected elements with the specified text.

Syntax:

$(selector).text(content);
  • selector: The target HTML element (such as an ID, class, or tag name).
  • content: The new string to insert into the element.

Basic Example

Consider the following HTML markup:

<p id="message">Original text</p>
<button id="updateBtn">Change Text</button>

To update the paragraph text when the button is clicked, write:

$('#updateBtn').click(function() {
    $('#message').text('The text has been updated successfully.');
});

When triggered, jQuery finds the element with the ID message and replaces its inner content with the new string.

Setting Text on Multiple Elements

If a selector matches multiple elements, .text() updates all of them simultaneously.

<div class="status">Pending</div>
<div class="status">Pending</div>
$('.status').text('Completed');

Running this code changes the inner text of both div elements to "Completed".

Using a Callback Function

jQuery also allows you to pass a function to .text(). This is useful when you want to compute the new text based on the element's index or its current text.

$('li').text(function(index, currentText) {
    return (index + 1) + '. ' + currentText;
});

The function receives two arguments: the zero-based index of the element within the set and the original text content. The returned value becomes the new text.

Difference Between .text() and .html()

It is important not to confuse .text() with .html():

  • .text() treats all input as plain text. If you pass an HTML string (such as <strong>Hello</strong>), jQuery automatically escapes the characters, displaying the raw HTML tags as literal text on the screen. This makes .text() safe against Cross-Site Scripting (XSS) when handling untrusted user input.
  • .html() parses and renders HTML tags. Use this method only when you intend to insert and render HTML elements inside the target container.