JavaScript Element insertAdjacentHTML() Method

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

What You’ll Learn

Element.insertAdjacentHTML() is an instance method that parses an HTML string and inserts the resulting nodes at one of four positions: beforebegin, afterbegin, beforeend, and afterend. Learn the MDN position diagram, comparison with insertAdjacentElement(), XSS safety basics, and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Returns

undefined

03

Args

pos + HTML

04

Parses

HTML/XML

05

Safety

XSS aware

06

Status

Baseline widely

Introduction

Sometimes you have a small HTML snippet — a list item, a badge, or a paragraph with formatting — and you want to drop it into the page at an exact spot. insertAdjacentHTML(position, htmlString) parses that string and inserts the nodes relative to your target element.

MDN: the method parses the specified input as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It uses the same four position names as insertAdjacentElement().

⚠️
Security note (MDN)

insertAdjacentHTML() is an injection sink. Never pass untrusted user input directly. Sanitize HTML first, or use insertAdjacentText() when you only need plain text.

This page is part of JavaScript Element. Pair it with insertAdjacentElement() when you already have an Element node instead of a string.

Understanding the insertAdjacentHTML() Method

Calling target.insertAdjacentHTML(position, input) parses input and inserts nodes relative to target.

  • It is an instance method on Element.
  • First argument: position string (beforebegin, afterbegin, beforeend, afterend).
  • Second argument: HTML or XML string to parse (MDN).
  • Returns undefined (MDN).
  • Does not reparse the target element’s existing children (MDN).
  • Often faster than rewriting innerHTML on the whole parent.
  • MDN: APIs like this can enable XSS if input comes from an attacker.

📝 Syntax

General form of Element.insertAdjacentHTML (MDN):

JavaScript
insertAdjacentHTML(position, input)

Parameters

position — One of "beforebegin", "afterbegin", "beforeend", or "afterend" (MDN).

input — A string defining the HTML or XML to be parsed (MDN).

Return value

None (undefined) (MDN).

Position diagram (MDN)

JavaScript
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

Common patterns

JavaScript
// MDN: insert parsed HTML at selected position
const html = "<strong>inserted text</strong>";
subject.insertAdjacentHTML(positionSelect.value, html);

// Append snippet inside container
list.insertAdjacentHTML("beforeend", "<li>New item</li>");

// Prepend banner inside panel
panel.insertAdjacentHTML("afterbegin", '<div class="banner">Notice</div>');

// Plain user text? Use insertAdjacentText instead (MDN)
note.insertAdjacentText("beforeend", userComment);

⚡ Quick Reference

GoalCode
Append HTML insideel.insertAdjacentHTML("beforeend", html)
Prepend HTML insideel.insertAdjacentHTML("afterbegin", html)
Before elementel.insertAdjacentHTML("beforebegin", html)
After elementel.insertAdjacentHTML("afterend", html)
Return valueundefined
MDN statusBaseline Widely available (since April 2018)

🔍 At a Glance

Four facts to remember about Element.insertAdjacentHTML().

Returns
void

undefined

Baseline
widely

Since Apr 2018

Args
pos+str

HTML string

Risk
XSS

Sanitize

📋 HTML insertion APIs

insertAdjacentHTML()insertAdjacentElement()innerHTML
InputHTML stringElement nodeHTML string (replaces)
Positions4 relative slots4 relative slotsWhole element only
ReturnsundefinedElement or nullundefined
Existing kidsNot reparsed (MDN)UnchangedReplaced / reparsed
Best forHTML snippetsBuilt Element nodesReplace all content

Examples Gallery

Examples follow MDN Element.insertAdjacentHTML() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN four-position HTML insertion.

Example 1 — MDN Four Positions

Insert parsed HTML at the selected position (MDN demo pattern).

JavaScript
const subject = document.getElementById("subject");
const position = document.getElementById("position").value;
const html = "<strong>inserted text</strong>";

subject.insertAdjacentHTML(position, html);

// position is one of:
// "beforebegin" | "afterbegin" | "beforeend" | "afterend"
Try It Yourself

How It Works

MDN’s example lets you pick a position and inserts bold HTML relative to the target element. The browser parses the string into real nodes.

Example 2 — afterbegin Banner

Prepend an HTML snippet as the first child inside a panel.

JavaScript
const panel = document.getElementById("panel");

panel.insertAdjacentHTML(
  "afterbegin",
  '<div class="banner">New notice</div>'
);

console.log(panel.firstElementChild.className); // "banner"
Try It Yourself

How It Works

afterbegin parses the HTML string and inserts the nodes just inside the element, before existing children (MDN).

📈 Practical Patterns

Append snippets, sibling HTML, and safe usage.

Example 3 — beforeend List Item

Append a new list item from an HTML string.

JavaScript
const list = document.getElementById("list");

list.insertAdjacentHTML("beforeend", "<li>New task</li>");
console.log(list.children.length); // +1 item
Try It Yourself

How It Works

beforeend is a quick way to append parsed markup inside a container without replacing innerHTML (MDN).

Example 4 — afterend Sibling HTML

Insert HTML immediately after a target element.

JavaScript
const card = document.getElementById("card");

card.insertAdjacentHTML(
  "afterend",
  '<p class="hint">Saved just now</p>'
);

console.log(card.nextElementSibling.className); // "hint"
Try It Yourself

How It Works

afterend adds a sibling after the target. MDN: only valid when the element has an element parent in the DOM tree.

Example 5 — Safe vs Unsafe Input

Never pass raw user strings; use trusted markup or plain text APIs (MDN).

JavaScript
const userComment = getUserInput(); // untrusted

// Risky — XSS if userComment contains HTML (MDN)
// box.insertAdjacentHTML("beforeend", userComment);

// Safer for plain text — use insertAdjacentText (MDN)
box.insertAdjacentText("beforeend", userComment);

// Or sanitize HTML with a library before insertAdjacentHTML
Try It Yourself

How It Works

MDN classifies insertAdjacentHTML() as an injection sink. For user content, prefer insertAdjacentText() or sanitize HTML first.

🚀 Common Use Cases

  • Injecting small HTML templates at precise positions (MDN four slots).
  • Appending chat messages or notifications with beforeend.
  • Prepending alerts inside a panel with afterbegin.
  • Adding helper text after a field with afterend.
  • Faster partial updates than rewriting parent innerHTML (MDN).
  • Rendering trusted server-generated markup snippets in SPAs.

🧠 How insertAdjacentHTML() Inserts Markup

1

Choose position + HTML

target.insertAdjacentHTML("beforeend", html)

Args
2

Parse HTML string

Browser parses input as HTML or XML into nodes (MDN).

Parse
3

Insert at position

Nodes are placed relative to the target without reparsing existing children (MDN).

DOM
4

Done — returns undefined

Query the DOM if you need a reference to inserted nodes. Sanitize untrusted HTML first (MDN).

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available, April 2018).
  • Returns undefined — no inserted node reference (MDN).
  • MDN XSS warning: do not pass untrusted strings without sanitization.
  • Does not reparse the target element’s existing children (MDN).
  • beforebegin / afterend require an element parent in the tree (MDN).
  • Related: insertAdjacentElement(), append(), insertAdjacentText(), JavaScript hub.

Browser Support

Element.insertAdjacentHTML() is Baseline Widely available (MDN: across browsers since April 2018). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.insertAdjacentHTML()

Parse and insert HTML at beforebegin, afterbegin, beforeend, or afterend — returns undefined.

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Not supported
No
insertAdjacentHTML() Excellent

Bottom line: Use insertAdjacentHTML() for trusted HTML snippets at precise positions. Sanitize user input; prefer insertAdjacentText() for plain text.

Conclusion

Element.insertAdjacentHTML() parses an HTML string and inserts the resulting nodes at one of four positions around a target element. It is fast and flexible, but requires care with untrusted input.

Continue with insertAdjacentElement(), append(), shadowRoot, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use the MDN four-position diagram to pick the right slot
  • Sanitize HTML from users before inserting (MDN)
  • Use insertAdjacentText() for plain text comments
  • Prefer this over rewriting parent innerHTML for partial updates
  • Keep HTML snippets small and template-like

❌ Don’t

  • Pass raw user input directly (XSS risk per MDN)
  • Expect a return value reference to inserted nodes
  • Use for large page rewrites (consider templating instead)
  • Confuse afterbegin with beforebegin
  • Insert into detached nodes with beforebegin / afterend

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.insertAdjacentHTML()

Parse and insert HTML at four positions.

5
Core concepts
📄 02

Input

HTML str

Parse
📄 03

Inside

begin/end

Child
⚠️ 04

XSS

sanitize

Safe
05

vs

Element

Node

❓ Frequently Asked Questions

It parses an HTML or XML string and inserts the resulting nodes at a position relative to the element (MDN). Positions: beforebegin, afterbegin, beforeend, afterend.
No. MDN marks Element.insertAdjacentHTML() as Baseline Widely available (across browsers since April 2018). It is not Deprecated, Experimental, or Non-standard.
Nothing useful — the return value is undefined (MDN).
insertAdjacentHTML() takes an HTML string and parses it. insertAdjacentElement() inserts an existing Element node.
MDN warns it is an injection sink (XSS risk). Never pass untrusted strings directly. Sanitize input or use insertAdjacentText() for plain text.
MDN: it does not reparse the whole element, so existing children are not corrupted. It is often faster than replacing innerHTML on the parent.
Did you know?

MDN: unlike setting innerHTML on the parent, insertAdjacentHTML() does not reparse existing children inside the target element, which makes partial updates faster and safer for surrounding markup.

More Element Topics

Browse Element methods and properties to keep building your DOM skills.

insertAdjacentText() →

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