jQuery .html() Method

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

What Is .html()?

.html() gets or sets an element’s HTML contents via innerHTML (since jQuery 1.0). No args → read the first match. With a string → replace children of every match. Not available on XML documents.

Remember
var markup = $("#box").html();           // get (first match)
$("#box").html("<strong>Hi</strong>");    // set (replace children)
$("div").html(function (i, old) {        // callback since 1.4
  return old + " <em>#" + i + "</em>";
});
NeedUse
Read / write markup$(el).html() / .html(str)
Plain text only$(el).text()
Add without wiping$(el).append()
Clear children$(el).empty()

How to Use .html()

Decide whether you are reading or replacing inner markup.

  1. Select the element(s).
  2. Call .html() with no args to read the first match.
  3. Pass an HTML string to replace all children of every match.
  4. Or pass a function (index, oldhtml) since 1.4 to build new markup per element.
PieceRequired?Role
Matched setYesElement(s) to read or update
htmlStringFor setterTrusted markup that replaces children
functionOptional (1.4+)Returns new HTML; gets index, oldhtml

Pseudocode

Pseudocode
if no argument:
    return innerHTML of first matched element
    // (undefined if empty set)

if argument is a function:
    for each matched element el at index i:
        old = el.innerHTML
        empty el (clear children + clean data/handlers)
        newHtml = function.call(el, i, old)
        set el.innerHTML = newHtml
else:
    for each matched element el:
        replace all children with parsed htmlString
        // child data/handlers cleaned first

return original matched set (setter)

Cheat Sheet

Keep these facts handy while editing markup.

TopicDetail
Get.html() → first match only
Set.html(htmlString) → every match
Callback.html(fn) since 1.4
SincejQuery 1.0
EngineBrowser innerHTML
XMLNot supported
SecurityUntrusted strings → XSS risk

Live Preview

Get, set, or clear the sample box’s HTML.

Browser demo of .html() get / set — same idea as the examples below.

Hello world
Result
$("#box").html()
→ Hello <em>world</em>

jQuery Examples

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

Example 1 — Get HTML

Read the inner markup of the first matched element.

jQuery
var markup = $("#box").html();
// e.g. "Hello <em>world</em>"
Try It Yourself

How It Works

  1. Select. $("#box") finds the target.
  2. Get. No argument → read innerHTML.
  3. First only. Extra matches are ignored by the getter.
  4. String. You get markup as text, not a live jQuery set.

Example 2 — Set HTML

Replace everything inside each matched element.

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

How It Works

  1. Select. Every div is matched.
  2. Clean. Old children lose jQuery data/handlers, then are removed.
  3. Parse. The string becomes DOM nodes via innerHTML.
  4. Replace. Previous content is gone — not appended.

Example 3 — .html() vs .text()

Read markup, then turn it into visible text (tags shown as characters).

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

How It Works

  1. Get. .html() returns markup including tags.
  2. Set text. .text(htmlString) inserts that string as plain text.
  3. Result. Users see <b>...</b> characters, not bold formatting.
  4. Lesson. Markup vs text are different jobs — pick deliberately.

Example 4 — Callback Form

Build new HTML from the old value (since jQuery 1.4).

jQuery
$("#box").html(function (index, oldhtml) {
  return oldhtml + " <em>#" + index + "</em>";
});
Try It Yourself

How It Works

  1. Empty first. jQuery clears the element before calling your function.
  2. oldhtml. Use the second argument — do not re-read .html() inside.
  3. index. Zero-based position in the matched set.
  4. Return. Your return value becomes the new inner HTML.

Example 5 — Set, Then Style Inserted Nodes

Insert markup, then select and tweak what you just added.

jQuery
$("div").html("Wow! <b>Such excitement...</b>");
$("div b")
  .append(document.createTextNode("!!!"))
  .css("color", "red");
Try It Yourself

How It Works

  1. Insert. .html() places the new markup.
  2. Reselect. $("div b") finds the inserted <b>.
  3. Append. Adds text nodes after the bold text.
  4. Style. .css() colors the bold element (demo only).

Edge Cases & Pitfalls

Check these before shipping markup updates.

xss

Untrusted strings are unsafe

Scripts and event attributes in HTML strings can run. Sanitize, escape, or use .text().

getter

Getter is first-match only

$("div").html() never concatenates every div — only the first.

callback

Element is emptied before the callback

Rely on oldhtml, not a nested .html() read inside the function.

form

Textareas need .text() / .val()

Official guidance: a <textarea> does not contain HTML — do not use .html() for its value.

Browser Support

.html() has been part of jQuery since 1.0. The function callback arrived in 1.4. It uses the browser’s innerHTML and works wherever your loaded jQuery version runs (HTML documents only).

✓ Stable · jQuery 1.0+

jQuery .html()

Supported in all browsers that run jQuery 1.0+. Prefer a current jQuery 3.x build for modern projects.

100% jQuery core method
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: Safe for everyday UI with trusted markup. Never feed untrusted strings into .html().

Performance Notes

ApproachCostBest for
.html() getCheapReading one container
.html(small)ModerateSwapping panel markup
Huge HTML strings oftenExpensiveAvoid — update smaller pieces

Setting HTML rebuilds the subtree. For frequent small changes, prefer .text(), .append(), or updating one node.

Key Takeaways

  • Get: first match only; returns an HTML string.
  • Set: replaces all children of every match.
  • Safety: untrusted input → use .text() or sanitize.
  • Vs append: html replaces; append adds.

One line: .html() is jQuery’s get/set for innerHTML — powerful for trusted markup, dangerous for untrusted strings.

Frequently Asked Questions

With no arguments, .html() returns the HTML contents (innerHTML) of the first matched element. With an argument, it replaces all children inside every matched element. Available since jQuery 1.0. Not available on XML documents.
.html() reads or writes markup — tags are parsed when setting. .text() reads or writes plain text only. Prefer .text() for untrusted or plain strings; use .html() only with trusted markup.
.html() replaces all existing inner content. .append() adds content as the last child and keeps what was already there.
No. The getter returns only the first element's innerHTML. Use .each() if you need every element's HTML.
Yes, since jQuery 1.4: .html(function(index, oldhtml)). jQuery empties the element before the function runs; use oldhtml for the previous markup. Return the new HTML string.
No. Setting HTML from untrusted sources can cause XSS via script tags or event attributes. Escape or sanitize first, or use .text() instead.
Both clear contents. Prefer .empty() when your intent is “clear this container.” Prefer .html(string) when you are replacing markup in one step.

Next: .prependTo()

Insert matched elements at the start of a target container.

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

8 people found this page helpful