JavaScript Element innerHTML Property

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline
Instance property

What You’ll Learn

Element.innerHTML is a read/write instance property that gets or sets the HTML markup inside an element. Learn how to read and replace contents safely, when to prefer textContent, and how XSS risks appear—with five examples and try-it labs.

01

Kind

Instance property

02

Access

Get and set

03

Type

string

04

Effect

Replace children

05

Status

Baseline widely

06

Caution

XSS / untrusted HTML

Introduction

Need the HTML inside a box as a string—or replace that box’s children with new markup? innerHTML does both. Reading serializes descendants; writing parses a string into a new child tree.

It is powerful and common, but MDN warns it is an injection sink: untrusted strings can become XSS. For plain text from users, prefer textContent.

JavaScript
const box = document.querySelector("#example");
console.log(box.innerHTML);
box.innerHTML = "<p>Updated</p>";
💡
Beginner tip

Reading returns markup inside the element (not the element tag itself). For the element plus its contents, see outerHTML.

Understanding the Property

MDN: the innerHTML property of the Element interface gets or sets the HTML or XML markup contained within the element.

  • Get — string serialization of descendant nodes.
  • Set — parse HTML and replace all children.
  • null clearsel.innerHTML = null acts like "".
  • Baseline — widely available since July 2015 (MDN).

📝 Syntax

JavaScript
innerHTML

Value

Getting returns a string of the element’s HTML contents. Setting accepts a string (or TrustedHTML where enforced) and replaces descendants with the parsed result.

ItemDetail
Typestring (get); string or TrustedHTML (set)
AccessGet and set
Replace vs insertUse insertAdjacentHTML() to insert without full replace
Plain textPrefer textContent for untrusted user text
⚠️
Security

Never assign untrusted HTML from users or APIs without sanitizing. Event-handler attributes (for example onerror on an image) can run script when HTML is injected.

📋 MDN Read Example Shape

MDN reads the markup inside a container:

JavaScript
<div id="example">
  <p>My name is Joe</p>
</div>
JavaScript
const myElement = document.querySelector("#example");
const contents = myElement.innerHTML;
console.log(contents);
// "\n  <p>My name is Joe</p>\n" (whitespace may vary)

Related learning: outerHTML, textContent, and insertAdjacentHTML().

⚡ Quick Reference

GoalCode / note
Read HTML insideel.innerHTML
Replace childrenel.innerHTML = "<p>Hi</p>"
Clearel.innerHTML = "" (or null)
Plain text onlyel.textContent = userText
Insert without replaceel.insertAdjacentHTML("beforeend", html)
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about Element.innerHTML.

Kind
get / set

Instance

Type
string

HTML markup

Set does
replace

All children

Baseline
widely

Jul 2015+

Examples Gallery

Examples follow MDN Element: innerHTML. Labs use trusted static strings so you can practice safely.

📚 Getting Started

Read and replace markup like MDN’s container examples.

Example 1 — Read innerHTML

Serialize the HTML inside a container.

JavaScript
const myElement = document.querySelector("#example");
console.log(myElement.innerHTML.trim());
Try It Yourself

How It Works

The getter walks the child tree and builds an HTML string. Whitespace in the source can appear in the result—trim() helps for demos.

📈 Replace, Clear & Safety

Rewrite contents, empty a node, and compare with textContent.

Example 2 — Replace Contents

Assigning a string rebuilds the child DOM from HTML.

JavaScript
const box = document.querySelector("#box");
box.innerHTML = "<strong>Hello</strong> world";
console.log(box.firstElementChild.tagName);
console.log(box.textContent);
Try It Yourself

How It Works

The browser parses the string into nodes and replaces previous children. Old event listeners on removed nodes are gone with them.

Example 3 — Clear Contents

Empty string (or null) removes all descendants.

JavaScript
const box = document.querySelector("#box");
console.log(box.children.length); // 1
box.innerHTML = "";
console.log(box.children.length); // 0
console.log(box.innerHTML); // ""
Try It Yourself

How It Works

Per MDN, setting null is coerced to "", so both clear the element.

Example 4 — vs textContent

Tags in a string become real elements only with innerHTML.

JavaScript
const a = document.getElementById("a");
const b = document.getElementById("b");
a.innerHTML = "<em>Hi</em>";
b.textContent = "<em>Hi</em>";
console.log(a.firstElementChild !== null); // true (EM)
console.log(b.firstElementChild); // null (literal text)
Try It Yourself

How It Works

Use textContent when the value should never be HTML. That is the safest default for user-provided strings.

Example 5 — Support Snapshot

Feature-detect and remember the XSS tip.

JavaScript
console.log({
  supported: "innerHTML" in Element.prototype,
  returns: "string (HTML of descendants)",
  tip: "Use textContent for plain / untrusted text",
  status: "Baseline Widely available (MDN)"
});
Try It Yourself

How It Works

Widely supported. Treat every assignment as parsing HTML—only inject markup you trust or have sanitized.

🚀 Common Use Cases

  • Reading a template fragment as an HTML string for debugging or cloning patterns.
  • Replacing a panel’s contents with trusted static markup.
  • Clearing a container before rebuilding UI (innerHTML = "").
  • Quick demos and tutorials (prefer safer APIs in production for untrusted data).
  • Pairing with insertAdjacentHTML when you need to append instead of replace.

🔧 How It Works

1

Element has descendants

Child nodes form the current inner tree.

DOM
2

Get serializes; set parses

Read builds a string; write runs the HTML parser.

Parse
3

Children are replaced

Old nodes are removed; new ones become the contents.

Replace
4

Trust the string you assign

Sanitize or use textContent for untrusted input.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available).
  • MDN flags innerHTML as a common XSS vector—never inject untrusted HTML raw.
  • Shadow roots are omitted from serialization; use getHTML() when you need them.
  • Related: id, outerHTML, textContent, lastElementChild, JavaScript hub.

Browser Support

Element.innerHTML is Baseline Widely available (MDN: across browsers since July 2015; some details vary). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.innerHTML

Get/set — HTML string of descendants; setting replaces all children (XSS-sensitive).

Baseline Widely available
Google Chrome Supported
Yes
Microsoft Edge Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Opera Supported
Yes
Internet Explorer Supported
Yes
innerHTML Baseline

Bottom line: Use innerHTML to read or replace an element's HTML contents. Prefer textContent for plain text, and never assign untrusted HTML without sanitizing.

Conclusion

innerHTML gets and sets the HTML inside an element. It is perfect for trusted markup updates, but treat every write as HTML parsing—use textContent for plain text and sanitize anything you do not fully control.

Continue with lastElementChild, id, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use textContent for user-provided plain text
  • Only assign innerHTML with trusted or sanitized HTML
  • Prefer insertAdjacentHTML when appending instead of replacing
  • Clear with innerHTML = "" when rebuilding a container
  • Remember listeners on removed nodes are discarded

❌ Don’t

  • Pipe raw form or API strings into innerHTML
  • Assume <script> tags will run when injected this way
  • Ignore XSS risks from attributes like onerror
  • Use innerHTML when you only need text updates
  • Expect shadow roots in the serialized string

Key Takeaways

Knowledge Unlocked

Five things to remember about innerHTML

Get/set HTML inside an element—powerful, XSS-sensitive.

5
Core concepts
📝 02

HTML string

descendants

Type
🔍 03

Replace

all children

Use
04

Baseline

widely available

Status
🎯 05

XSS care

trust / sanitize

Tip

❓ Frequently Asked Questions

It gets or sets the HTML markup inside an element. Reading returns a string of the descendants; writing parses HTML and replaces all children.
No. MDN marks Element.innerHTML as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
Only with trusted markup. Untrusted strings can cause XSS. Prefer textContent for plain text, or sanitize / Trusted Types before injecting HTML.
textContent treats values as plain text (no HTML parsing). innerHTML parses tags into real DOM elements.
null is converted to an empty string, so el.innerHTML = null clears the element the same as el.innerHTML = "".
Use insertAdjacentHTML when you want to insert HTML next to an element without replacing its entire contents.
Did you know?

Injected <script> tags via innerHTML typically do not execute, but many other HTML patterns (like image onerror handlers) still can—so XSS risk remains real.

Next: lastElementChild

Learn how Element.lastElementChild reads the last nested tag child.

lastElementChild →

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.

5 people found this page helpful