jQuery text() Method

Beginner
6 min read
Updated: Oct 2026
5 examples
Live preview

What Is text()?

.text() gets or sets plain text content (since jQuery 1.0). The getter returns the combined text of all matched elements, including descendants. The setter escapes HTML via createTextNode — tags are shown as characters, not markup. Works in both HTML and XML.

Remember
var s = $("div.demo").text()     // get combined text
$("p").text("Hello")             // set plain text
$("p").text("<b>Hi</b>")         // tags escaped — not bold

// vs html (parses markup) and val (form values):
$("p").html("<b>Hi</b>")
$("input").val("Hello")
NeedUse
Plain text get/set.text() / .text(str)
HTML markup.html()
Form field value.val()
Clear contents.empty()

How to Use text()

Select elements, then get combined text or set escaped text.

  1. Select the element(s) whose text you need.
  2. Call .text() with no args to read the combined string.
  3. Call .text(value) to replace contents with escaped plain text.
  4. Or pass a function (1.4+) that returns the new text per element.
PieceRequired?Role
jQuery collectionYesElements to read or update
textNo*String, Number, or Boolean to set
functionAlt*(index, oldText) => newText (1.4+)
Return (get)—Combined string
Return (set)—jQuery collection for chaining

* Omit arguments to get; pass text or a function to set.

Pseudocode

Pseudocode
// Getter
parts = []
for each element in matched set:
  parts.push(all descendant text)
return parts joined as one string

// Setter
for each element in matched set:
  clear children
  append createTextNode(String(value))  // HTML escaped
return matched set

// Function setter (1.4+)
for each element (index i):
  newText = fn(i, oldText)
  set text to newText

Cheat Sheet

Keep these facts handy while reading or writing text.

TopicDetail
Syntax.text() · .text(value) · .text(fn)
Since1.0 (function form 1.4)
GetterAll matches + descendants combined
SetterEscapes HTML (safe for user strings)
vs .html()Plain text vs markup
vs .val()Element text vs form value
XMLWorks in HTML and XML documents
WhitespaceMay vary slightly by browser parser

Live Preview

Get or set text on a tiny demo tree and see escaping vs markup.

Browser demo of .text() — same idea as the examples below.

Result
Ready — pick an action.

jQuery Examples

Short, copy-ready snippets. Open DevTools Console, or use Try It Yourself for a live editor.

Example 1 — Get Combined Text

Read all descendant text from a container as one string.

jQuery
// <div class="demo">
//   Demonstration Box
//   <ul><li>list item 1</li><li>list item 2</li></ul>
// </div>
console.log($("div.demo").text());
Try It Yourself

How It Works

  1. Select. The container and all descendants are in scope.
  2. Collect. Every text node is gathered.
  3. Combine. One string is returned (whitespace may vary by browser).
  4. No tags. Markup is not included — only text.

Example 2 — Official Demo: Set Escaped Text

Pass a string with tags — they appear as characters, not HTML.

jQuery
$("p").text("<b>Some new text.</b>");
// Visible as: <b>Some new text.</b>  (not bold)
Try It Yourself

How It Works

  1. Replace children. Old content is cleared.
  2. Text node. jQuery uses createTextNode.
  3. Escaped. <b> is literal text, not a bold element.
  4. Safe default. Prefer this for user-supplied strings.

Example 3 — Official Demo: Strip Then Show

Copy text from the first paragraph into the last via .html().

jQuery
var str = $("p").first().text();
$("p").last().html(str);
Try It Yourself

How It Works

  1. Read. First p text strips inner <b>.
  2. Plain string. No markup remains in str.
  3. Write. Last p gets that string via .html().
  4. Lesson. .text() is how you drop tags from content.

Example 4 — Callback Form (1.4+)

Set each list item from its index.

jQuery
$("ul li").text(function (index) {
  return "item number " + (index + 1);
});
Try It Yourself

How It Works

  1. Per element. The function runs once for each li.
  2. Index. First argument is 0-based position.
  3. Return. The returned string becomes that item’s text.
  4. Old text. Second argument is the previous text if you need it.

Example 5 — text vs html

Same string, different results — escaped vs parsed.

jQuery
$("#a").text("<b>Hi</b>");   // shows the tags
$("#b").html("<b>Hi</b>");   // renders bold Hi
Try It Yourself

How It Works

  1. text. Creates a text node — tags are visible characters.
  2. html. Parses markup — a real <b> element appears.
  3. Security. Untrusted strings → .text().
  4. Trusted markup. Only then consider .html().

Edge Cases & Pitfalls

Check these before reading or writing text in real pages.

forms

Inputs need .val()

.text() is the wrong API for input / textarea values.

getter

All matches are combined

Unlike .html(), the getter joins every matched element’s text.

whitespace

Whitespace can differ

Browsers may vary newlines and spaces in the returned string.

overwrite

Setter replaces all children

Nested elements are removed when you set text on a parent.

types

Numbers and booleans

Non-strings are converted to their string form when setting.

Browser Support

.text() is a core jQuery method (since 1.0; function form 1.4). It needs a browser DOM with jQuery loaded.

✓ jQuery 1.0+ · Browsers only

jQuery .text()

Works in Chrome, Firefox, Safari, Edge, and other browsers with jQuery. Not for Node.js without a DOM.

100% Browser support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
.text() Browsers

Bottom line: Use .text() in the browser for safe plain-text get/set. Prefer it over .html() for user-supplied strings.

Performance Notes

ApproachCostBest for
.text() getLow–mediumReading labels / combined text
.text(str) setLowSafe updates without parsing HTML
.html(str)HigherTrusted markup only

Setting text is usually cheaper and safer than parsing HTML. Getting text from a huge tree walks many nodes — prefer a narrower selector when possible.

Key Takeaways

  • Role: get combined text or set escaped plain text.
  • Safe: setter escapes HTML — prefer for user strings.
  • vs html / val: plain text vs markup vs form values.
  • Getter: joins every matched element’s text.

One line: $(sel).text() reads plain text; .text(str) writes it safely without parsing HTML.

Frequently Asked Questions

With no arguments, .text() returns the combined text of all matched elements, including descendants. With an argument, it replaces children with a text node — HTML is escaped, not parsed. Works in HTML and XML. Available since jQuery 1.0; function form since 1.4.
.text() reads/writes plain text only. .html() reads/writes markup. Setter .text() escapes tags; .html() parses them. Prefer .text() for user strings.
.text() is for element contents (div, p, span). .val() is for form controls (input, textarea, select). Do not use .text() on inputs.
Yes. Unlike .html() (first element only), .text() concatenates text from every matched element and their descendants into one string.
Yes, since 1.4. .text(function(index, text)) runs once per element; return the new string. this is the current DOM element.
Yes. It uses createTextNode, so angle brackets show as characters instead of markup. Prefer .text() over .html() for names, comments, and messages.

Next: after()

Insert content after each matched element.

after() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful