The .text() method gets or sets the plain text contents of matched elements — a getter that returns combined text from all matches including descendants, and a setter that replaces all children with escaped text. This tutorial covers both forms since 1.0, the callback setter since 1.4, comparisons with .html(), .val(), and .empty(), the official jQuery demos, and five practical try-it examples.
01
Getter
Read text
02
Setter
Replace all
03
Callback
Since 1.4
04
vs .html()
Plain text
05
Safe
No XSS
06
Since 1.0
HTML & XML
Fundamentals
Introduction
User names, comment bodies, notification messages, and status labels are almost always plain text — not HTML markup. jQuery provides .text() to read visible text from the page and write safe strings that never execute as scripts or render as tags.
Available since jQuery 1.0, .text() works in both HTML and XML documents (unlike .html()). Called with no arguments, it returns the combined text of every matched element and their descendants. Called with a string, number, boolean, or callback, it replaces all children with a single text node — jQuery escapes HTML automatically via createTextNode().
Do not use .text() on form inputs — use .val() instead. Use .html() only when you need to parse trusted markup. Browse the jQuery DOM hub for related manipulation methods.
Concept
Understanding the .text() Method
Getter:.text() returns a string containing the combined text contents of all matched elements, including descendant text nodes. Tags are stripped — only visible characters remain.
Setter:.text( textString ) or .text( function ) replaces every child inside each matched element with one text node. Numbers and booleans are converted to strings. HTML in the argument is escaped, not parsed. Returns the jQuery collection for chaining.
💡
Beginner Tip
The official jQuery demo reads $("p").first().text() to strip bold tags from the first paragraph, then writes that plain string into the last paragraph with .html(str) to show it renders without formatting.
Foundation
📝 Syntax
jQuery .text() supports three forms:
Get text contents — since 1.0
jQuery
.text()
Returns combined text from all matched elements and their descendants.
Works in both HTML and XML documents.
Set text contents — since 1.0
jQuery
.text( textString )
Replaces all children inside each matched element.
textString — plain text; also accepts Number or Boolean (converted to String).
Set with callback — since 1.4
jQuery
.text( function( index, text ) {
// return new text string; `this` is the current element
} )
Callback receives index and old text value per matched element.
Four related content APIs — pick the right read, write, or clear strategy.
.text()
plain text
Get or set text content only — HTML escaped when setting, works in XML documents
.html()
innerHTML
Get or set HTML markup — setter parses tags, XSS risk with untrusted input
.val()
form value
Get or set input, textarea, and select values — not for div or span elements
.empty()
clear
Remove all children without setting new text — parent stays in DOM
Hands-On
Examples Gallery
Examples 1–5 follow the official jQuery API documentation and common production patterns. Use DevTools or the Try-it links to run each snippet in the browser.
📚 Getting Started
Official jQuery getter and setter demos.
Example 1 — Official Demo: Get Text, Display Without Bold
Read plain text from the first paragraph (stripping HTML), then set the last paragraph to show it without formatting.
First p: "Test Paragraph." (bold stripped)
Last p updated via .html(str) — no red bold tags
Official jQuery text getter demo
How It Works
The getter returns only visible characters — <b> tags are ignored. Writing the result with .html() inserts it as text content inside the paragraph, so formatting is gone but the words remain.
Example 2 — Official Demo: Set Text With HTML Escaped
Add text to a paragraph — notice the bold tag in the string is escaped, not rendered.
jQuery
$( "p" ).text( " Some new text with <b>bold</b> tags." );
Paragraph shows literal "<b>bold</b>" characters
Previous children replaced — not appended
Red bold styling from original content is gone
Official jQuery text setter demo
How It Works
jQuery calls createTextNode() under the hood. Angle brackets appear on screen as characters instead of creating HTML elements. This is why .text() is safe for user input.
📈 Practical Patterns
Combined text reading, callback setter, and safe user comments.
Example 3 — Get Combined Text From a Container
Read all visible text inside a demo container, including nested list items.
jQuery
var allText = $( "div.demo-container" ).text();
// "Demonstration Box list item 1 list item 2"
$( "#output" ).text( allText );
Combined string from container + descendants
Tags stripped — only text nodes included
Whitespace may vary slightly between browsers
How It Works
Unlike .html(), the getter concatenates text from every matched element. Useful for search indexing, copy-to-clipboard features, or displaying a plain-text preview of rich content.
Example 4 — Set Text With Callback (jQuery 1.4+)
Rename every list item dynamically using the callback form.
jQuery
$( "ul li" ).text( function( index ) {
return "item number " + ( index + 1 );
});
li items become "item number 1", "item number 2", ...
Callback receives index and old text value
Official jQuery 1.4 callback demo
How It Works
The callback runs once per matched element. Return the new string to set as text content. The second parameter holds the previous text if you need to transform it.
Example 5 — Display User Comments Safely
Show a user-submitted comment without XSS risk — the production pattern for dynamic labels.
jQuery
var userComment = formData.comment; // may contain <script> or tags
$( "#comment-display" ).text( userComment );
// NEVER: $( "#comment-display" ).html( userComment );
Malicious markup shown as literal characters
No script execution — createTextNode escapes HTML
Default choice for names, messages, and labels
Pair with server-side validation for defense in depth
How It Works
.text() never parses HTML from the argument. Even if a user submits <img onerror=alert(1)>, it displays as harmless text. Use .html() only when you intentionally render trusted markup.
Applications
🚀 Common Use Cases
User comments — display submitted text safely without XSS.
Status labels — update counters, badges, and notification text dynamically.
Strip HTML — getter removes tags for plain-text previews or search.
Combined reading — extract all visible text from a widget for copy or export.
Dynamic list labels — callback form renames items by index.
XML documents — read and write text where .html() is unavailable.
🧠 How .text() Gets and Sets Content
1
Check arguments
No args → getter mode. String, number, boolean, or function → setter mode.
Mode
2
Getter: collect text nodes
Walk matched elements and descendants; concatenate text content into one string.
Read
3
Setter: replace children
Remove existing children; insert createTextNode with escaped plain text.
Write
4
📝
Return result
Getter returns string; setter returns jQuery collection for chaining.
Important
📝 Notes
Available since jQuery 1.0 — works in HTML and XML documents.
Do not use on input, textarea, or select — use .val().
Do not use on script elements — use .html() to read script source.
Getter concatenates text from all matched elements (unlike .html() getter).
Setter accepts Number and Boolean — converted to String automatically.
Since jQuery 1.4, getter includes text and CDATA nodes, not just element nodes.
Whitespace in getter results may vary slightly between browser HTML parsers.
Compatibility
Browser Support
.text() has been part of jQuery since 1.0+. It relies on standard DOM textContent and createTextNode operations. Works in all browsers supported by your jQuery build — IE6+ through modern evergreen browsers in legacy jQuery versions, and all current browsers in jQuery 3.x and 4.x.
✓ jQuery 1.0+
jQuery .text()
Universal plain-text API across jQuery 1.x, 2.x, 3.x, and 4.x. Safe for user input in HTML and XML documents. Pair with .html() when you need markup rendering from trusted sources only.
100%With jQuery loaded
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
.text()Universal
Bottom line: Default choice for reading and writing plain text safely.
Wrap Up
Conclusion
The jQuery .text() method gets combined plain text from matched elements or sets escaped text that replaces all children. Use the getter to strip HTML tags, and the setter for user comments, labels, and notifications — exactly as the official jQuery demos demonstrate.
Choose .html() only for trusted markup, and .val() for form fields. Next up: inserting sibling content below matched elements with .after().
Use .text() for user names, comments, and notification messages
Use the getter to strip HTML before plain-text search or export
Use the callback form for per-element dynamic labels
Use .val() for input and textarea field values
Prefer .text() over .html() when markup is not needed
❌ Don’t
Use .html(untrustedInput) when .text() suffices
Call .text() on form inputs — use .val()
Expect the getter to return HTML — tags are always stripped
Assume getter returns only first element — it combines all matches
Rely on .text() alone for security — validate on server too
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about .text()
The safe plain-text API — read combined text or write escaped strings.
5
Core concepts
T01
Plain
Text only
Safe
+02
Combined
Getter
All matches
<>03
vs html
Markup
Compare
fn04
Callback
Since 1.4
Dynamic
XML05
HTML
& XML
Works
❓ Frequently Asked Questions
With no arguments, .text() returns the combined text contents of all matched elements, including descendant text nodes. With an argument, .text(textString) replaces all children with a single text node — HTML is escaped, not parsed. Available since jQuery 1.0. Works in both HTML and XML documents.
.text() reads or writes plain text only — tags are never parsed when setting. .html() reads or writes innerHTML markup. Use .text() for user-visible strings and labels; use .html() only with trusted markup.
.text() gets or sets text inside regular elements (div, p, span). .val() gets or sets the value of form inputs (input, textarea, select). Do not use .text() on input fields — use .val() instead.
Yes. Unlike .html(), which returns only the first element's innerHTML, the .text() getter concatenates text from every matched element and all their descendants into one string.
Since jQuery 1.4, yes. .text(function(index, text)) runs once per matched element. The callback receives the index and old text value; return the new string to set. Inside the function, this refers to the current DOM element.
Yes — .text() is the safe default for displaying user-supplied strings. jQuery uses createTextNode under the hood, so angle brackets and script tags appear as literal characters instead of executing. Prefer .text() over .html() for comments, names, and notification messages.
Did you know?
jQuery’s .text() setter uses document.createTextNode() internally, which is why HTML tags in the argument appear as literal characters on screen instead of rendering as elements. This makes .text() the recommended way to display user-generated content in jQuery apps. Unlike .html(), .text() also works on XML documents — a detail that matters when parsing RSS feeds or SVG fragments. Since jQuery 1.4, the getter includes CDATA section text, not just regular text nodes inside elements.