jQuery .html() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
DOM methods

What You’ll Learn

The .html() method gets or sets the HTML contents of matched elements — a getter that returns innerHTML from the first match, and a setter that replaces all children. This tutorial covers both forms since 1.0, the callback setter since 1.4, comparisons with .text(), .append(), and .empty(), the official jQuery demos, and five practical try-it examples.

01

Getter

Read HTML

02

Setter

Replace all

03

Callback

Since 1.4

04

vs .text()

Plain text

05

XSS

Stay safe

06

Since 1.0

Core API

Introduction

Templates, widgets, and Ajax responses often need to swap entire blocks of markup inside a container — replace a loading spinner with results, read existing HTML before transforming it, or render a partial from the server. jQuery provides .html() for both reading and writing inner HTML.

Available since jQuery 1.0, .html() works in two modes. Called with no arguments, it returns the HTML string inside the first matched element. Called with an HTML string or callback, it replaces all child content inside every matched element. The method uses the browser’s innerHTML property under the hood.

Setting HTML runs through the browser parser — never pass untrusted user input directly. Use .text() for plain strings and .append() when adding without wiping existing children. Browse the jQuery DOM hub for related manipulation methods.

Understanding the .html() Method

Getter: .html() returns a string of the first matched element’s inner HTML. If nothing matches, it returns undefined.

Setter: .html( htmlString ) or .html( function ) replaces every child node inside each matched element. jQuery cleans up data and event handlers on removed children before inserting new markup. Returns the jQuery collection for chaining.

💡
Beginner Tip

The official jQuery demo reads $(this).html() on paragraph click, then writes it back with $(this).text(htmlString) to strip tags and show raw markup as visible text.

📝 Syntax

jQuery .html() supports three forms:

Get HTML contents — since 1.0

jQuery
.html()
  • Returns a string of the first matched element’s innerHTML.
  • Not available on XML documents.

Set HTML contents — since 1.0

jQuery
.html( htmlString )
  • Replaces all children inside each matched element.
  • htmlString — HTML markup parsed by the browser.

Set with callback — since 1.4

jQuery
.html( function( index, oldhtml ) {
  // return new HTML string; `this` is the current element
} )
  • Element is emptied before callback runs; use oldhtml for previous content.

⚡ Quick Reference

GoalCode
Read inner HTML (first match)var markup = $("#panel").html()
Replace all inner content$("#panel").html("<p>Fresh</p>")
Set HTML with callback$("div").html(function(i, old){ return old + "!"; })
Set plain text safely$("#msg").text(userInput)
Add without replacing$("#list").append("<li>")
Clear children only$("#box").empty()

📋 .html() vs .text() vs .append() vs .empty()

Four related content APIs — pick the right read, write, or clear strategy.

.html()
innerHTML

Get or set HTML markup — setter replaces all children inside matched elements

.text()
plain text

Get or set text content only — no HTML parsing, safer for user input

.append()
add last

Insert content as last child — existing children remain

.empty()
clear

Remove all children without setting new HTML — parent stays in DOM

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 demo and basic setter patterns.

Example 1 — Official Demo: Get HTML, Display as Text

Click a paragraph to read its inner HTML with the getter, then show the raw markup as visible text.

jQuery
$( "p" ).on( "click", function() {
  var htmlString = $( this ).html();
  $( this ).text( htmlString );
});
Try It Yourself

How It Works

The getter returns the element’s inner HTML including tags. Assigning that string to .text() escapes rendering — users see markup characters instead of formatted bold text.

Example 2 — Official Demo: Set HTML on Every Div

Replace all inner content of matched divs with new HTML markup.

jQuery
$( "div" ).html( "<b>Hello Again</b>" );
Try It Yourself

How It Works

The setter wipes existing children and parses the HTML string. Event handlers on removed children are cleaned up by jQuery. Chain further selectors on newly inserted nodes after setting HTML.

📈 Practical Patterns

Callback setter, text safety, and Ajax panel updates.

Example 3 — Set HTML With Callback (jQuery 1.4+)

Generate dynamic HTML per element using the previous content via oldhtml.

jQuery
$( "div.demo-container" ).html( function( index, oldhtml ) {
  var emphasis = "<em>" + $( "p" ).length + " paragraphs!</em>";
  return "<p>All new content for " + emphasis + "</p>";
});
Try It Yourself

How It Works

jQuery empties each element before invoking the callback. Return a string to set as new HTML. Use oldhtml when the new markup should reference or transform previous content.

Example 4 — .html() vs .text() for User Input

Show why user-supplied strings belong in .text(), not .html().

jQuery
var userInput = "<img src=x onerror=alert(1)>";

// DANGEROUS — parses HTML, can execute scripts
$( "#unsafe" ).html( userInput );

// SAFE — displays literal characters
$( "#safe" ).text( userInput );
Try It Yourself

How It Works

.html() passes strings through the HTML parser. Malicious markup can inject scripts or event handlers. .text() treats input as plain text. Always sanitize or escape when HTML rendering is required.

Example 5 — Replace Panel Content From Ajax

Swap a loading state with server-rendered HTML using the setter.

jQuery
$( "#results" ).html( "<p class='loading'>Loading…</p>" );

$.get( "/api/partial", function( html ) {
  $( "#results" ).html( html );
});
Try It Yourself

How It Works

.html() replaces the full panel in one call — simpler than .empty().append() when swapping entire fragments. Only use server HTML you trust; jQuery’s .load() wraps this Ajax pattern conveniently.

🚀 Common Use Cases

  • Template swap — replace widget inner markup after user action or Ajax response.
  • Read before transform — getter captures HTML, modify, setter writes back.
  • Loading states.html("<p>Loading…</p>") then replace with results.
  • Clone markupvar tpl = $("#template").html() for string-based duplication.
  • Debug panels — display raw HTML source to developers via getter + text.
  • Dynamic emphasis — callback form builds HTML based on page state.

🧠 How .html() Gets and Sets Content

1

Match elements

jQuery collection points at containers whose inner HTML is read or written.

Select
2

Getter or setter?

No args → read first match innerHTML. With arg → replace all children.

Mode
3

Cleanup on set

jQuery removes old child data and events before inserting new HTML.

Memory
4

Return value

Getter → string. Setter → jQuery collection for chaining.

📝 Notes

  • Available since jQuery 1.0 — callback setter added in jQuery 1.4.
  • Getter returns only the first matched element’s innerHTML.
  • Setter replaces all children — unlike .append().
  • Not available on XML documents.
  • Uses browser innerHTML — returned HTML may differ slightly from source in older IE.
  • For <script> elements, use .text() to set content, not .html().
  • Never pass untrusted strings to the setter — XSS risk via parsed markup.

Browser Support

.html() has been part of jQuery since 1.0+, with the callback setter since 1.4+. It wraps the browser innerHTML property. Works in all HTML documents 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. Not for XML documents.

jQuery 1.0+

jQuery .html()

Universal innerHTML getter/setter across jQuery 1.x, 2.x, 3.x, and 4.x for HTML documents. Pair with .text() for safe plain-text insertion and .load() for Ajax-powered HTML replacement.

100% HTML documents
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
.html() Universal

Bottom line: Default choice for reading or fully replacing inner HTML of matched elements.

Conclusion

The jQuery .html() method reads innerHTML from the first matched element or replaces all children when setting. Use the callback form for dynamic markup, and prefer .text() for untrusted strings — exactly as the official getter and setter demos demonstrate.

Choose .append() when adding without wiping existing content, and .empty() when clearing without new markup. Next up: inserting at the top with .prepend().

💡 Best Practices

✅ Do

  • Use .html() to replace entire container markup from trusted sources
  • Use the getter on the first match when reading template HTML
  • Use .text() for user-visible plain text from forms or URLs
  • Use the callback setter when new HTML depends on old content
  • Prefer .load() for Ajax HTML injection from your server

❌ Don’t

  • Pass untrusted user input to .html() (XSS vulnerability)
  • Expect the getter to combine HTML from multiple matched elements
  • Use .html() when you only need to add items (use .append())
  • Set content on <script> tags with .html()
  • Call .html() on XML documents — method is unavailable

Key Takeaways

Knowledge Unlocked

Five things to remember about .html()

The innerHTML getter/setter — read first, replace all when setting.

5
Core concepts
1st 02

Getter

First only

Read
03

Setter

Replace all

Write
T 04

.text()

Safe text

XSS
fn 05

Callback

Since 1.4

Dynamic

❓ Frequently Asked Questions

With no arguments, .html() returns the HTML contents of the first matched element as a string (innerHTML). With an argument, .html(htmlString) replaces all children inside every matched element with the new HTML. Available since jQuery 1.0. Not available on XML documents.
.html() reads or writes HTML markup — tags are parsed when setting. .text() reads or writes plain text only — no HTML parsing. Use .text() for user-visible strings; use .html() only with trusted markup or escaped content.
.html() replaces all existing inner content when setting. .append() adds content as the last child without removing existing children. Use html to swap entire panel markup; use append to add items to a list.
No. The getter returns only the first element's innerHTML. If multiple elements match, call .html() in a loop or use .each() to read each one separately.
Since jQuery 1.4, yes. .html(function(index, oldhtml)) runs once per matched element. jQuery empties the element before the callback; use oldhtml to reference previous content. Return the new HTML string to set.
No — setting HTML from untrusted sources can cause XSS via script tags or event attributes. Escape or sanitize user input, or use .text() instead. Never pass URL parameters, cookies, or form values directly into .html().
Did you know?

jQuery’s .html() getter only reads the first matched element because returning multiple HTML strings would be ambiguous — unlike .text(), which concatenates text from all matches when getting. The setter, however, applies to every matched element simultaneously. Internet Explorer historically normalized innerHTML (dropping quotes, rewriting URLs), so never rely on round-tripping HTML strings for exact byte-for-byte equality across browsers. For script elements, jQuery documentation recommends .text() over .html() because HTML parsing of script content behaves inconsistently.

Next: jQuery .prepend() Method

Insert HTML, DOM nodes, or jQuery objects as the first child of matched elements.

.prepend() 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.

6 people found this page helpful