How to Retrieve Text Content Using jQuery

Retrieving text from an HTML element is a fundamental task in web development, and jQuery makes this process straightforward. This guide covers how to use jQuery's built-in .text() method to extract plain text from elements, explains how it handles child tags and multiple matched nodes, and highlights the key differences between .text(), .html(), and .val().

The .text() Method

The primary and most efficient way to get the text content of an element in jQuery is the .text() method. Unlike reading standard properties in native JavaScript, .text() automatically strips out any HTML tags and returns only the combined plain text.

// HTML: <div id="message">Hello, <span>World!</span></div>

let content = $('#message').text();
console.log(content); // Output: Hello, World!

Retrieving Text from Multiple Elements

When your selector matches more than one element, calling .text() retrieves and concatenates the text content of every matched element into a single string.

// HTML: 
// <ul id="list">
//   <li>Apple</li>
//   <li>Banana</li>
//   <li>Cherry</li>
// </ul>

let items = $('#list li').text();
console.log(items); // Output: AppleBananaCherry

If you need to process the text of each element individually, use the .each() method:

$('#list li').each(function() {
    console.log($(this).text());
});

Removing Extra Whitespace

HTML content often contains tabs, line breaks, or leading and trailing spaces. To clean up the retrieved string, combine jQuery's .text() with native JavaScript's .trim() method:

let cleanText = $('#message').text().trim();

.text() vs. .html() vs. .val()

It is important to select the correct jQuery method depending on the element type and data you need:

  • .text(): Returns only the text content, stripping all HTML tags. Use this for standard display elements like <div>, <p>, <span>, and <h1>.
  • .html(): Returns the inner markup along with the text. Use this when you need to preserve the underlying HTML tags inside the container.
  • .val(): Returns the values of form input elements. Use this for <input>, <textarea>, and <select> elements, as .text() does not read user-entered values in these fields.