JavaScript Element insertAdjacentElement() Method

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

What You’ll Learn

Element.insertAdjacentElement() is an instance method that inserts an Element node at one of four positions relative to the target element: beforebegin, afterbegin, beforeend, and afterend. Learn the MDN position diagram, comparison with append() and insertAdjacentHTML(), and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Returns

Element|null

03

Args

position + el

04

Inside

begin/end

05

Outside

before/after

06

Status

Baseline widely

Introduction

When you build dynamic UIs, you often need to place a new element in a precise spot: before a list item, as the first child of a panel, at the end of a container, or right after a card. insertAdjacentElement(position, element) does exactly that without manually calling parent.insertBefore().

MDN: the method inserts a given element node at a given position relative to the element it is invoked upon. You pass a position string and an Element to insert.

💡
Beginner tip

Think of four slots around an element. afterbegin and beforeend go inside the element (first/last child). beforebegin and afterend go outside as siblings.

This page is part of JavaScript Element. See also append() for adding children at the end, and before() for inserting siblings.

Understanding the insertAdjacentElement() Method

Calling target.insertAdjacentElement(position, newEl) places newEl relative to target.

  • It is an instance method on Element.
  • First argument: position string (case-insensitive per MDN).
  • Second argument: the Element node to insert.
  • Returns the inserted element, or null if insertion failed (MDN).
  • Throws SyntaxError if position is not recognized (MDN).
  • Throws TypeError if the second argument is not a valid element (MDN).
  • beforebegin / afterend require an element parent in the tree (MDN).

📝 Syntax

General form of Element.insertAdjacentElement (MDN):

JavaScript
insertAdjacentElement(position, element)

Parameters

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

element — The element node to insert into the tree (MDN).

Return value

The element that was inserted, or null if the insertion failed (MDN).

Position diagram (MDN)

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

Common patterns

JavaScript
// MDN: insert before or after a selected element
const newElement = document.createElement("div");
selectedElem.insertAdjacentElement("beforebegin", newElement);
selectedElem.insertAdjacentElement("afterend", newElement);

// Prepend inside container (first child)
const first = document.createElement("span");
container.insertAdjacentElement("afterbegin", first);

// Append inside container (last child)
const last = document.createElement("span");
container.insertAdjacentElement("beforeend", last);

// Check return value
const inserted = box.insertAdjacentElement("beforeend", item);
if (!inserted) console.log("insertion failed");

⚡ Quick Reference

GoalCode
Before elementel.insertAdjacentElement("beforebegin", node)
First child insideel.insertAdjacentElement("afterbegin", node)
Last child insideel.insertAdjacentElement("beforeend", node)
After elementel.insertAdjacentElement("afterend", node)
Failed insertnull
MDN statusBaseline Widely available (since April 2018)

🔍 At a Glance

Four facts to remember about Element.insertAdjacentElement().

Returns
Element

or null

Baseline
widely

Since Apr 2018

Args
pos+el

Two params

Positions
4

begin/end

📋 DOM insertion APIs

insertAdjacentElement()append()insertAdjacentHTML()
InsertsElement nodeNode(s) or stringsParsed HTML string
Positions4 relative slotsEnd only (last child)4 relative slots
ReturnsElement or nullundefinedundefined
Best forPrecise element placementQuick append at endHTML string snippets
MDN pairbefore/after siblingslike beforeendmarkup templates

Examples Gallery

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

📚 Getting Started

MDN insert-before/after and inside positions.

Example 1 — MDN Insert Before / After

Insert a new element before or after a selected node (MDN).

JavaScript
function insertNewElement(position) {
  if (!selectedElem) return;

  const newElement = document.createElement("div");
  newElement.textContent = "New";
  newElement.className = "box";

  selectedElem.insertAdjacentElement(position, newElement);
}

// MDN demo uses:
insertNewElement("beforebegin"); // before selected
insertNewElement("afterend");    // after selected
Try It Yourself

How It Works

MDN’s demo inserts colored boxes using beforebegin and afterend relative to the clicked element.

Example 2 — afterbegin (First Child)

Prepend a node as the first child inside a container.

JavaScript
const list = document.getElementById("list");
const first = document.createElement("li");
first.textContent = "First item";

list.insertAdjacentElement("afterbegin", first);
console.log(list.firstElementChild === first); // true
Try It Yourself

How It Works

afterbegin inserts just inside the element, before its first child — like prepending to a list (MDN).

📈 Practical Patterns

Append inside, sibling inserts, and return values.

Example 3 — beforeend (Last Child)

Append a node as the last child inside a container.

JavaScript
const panel = document.getElementById("panel");
const note = document.createElement("p");
note.textContent = "Added at end";

panel.insertAdjacentElement("beforeend", note);
console.log(panel.lastElementChild === note); // true
Try It Yourself

How It Works

beforeend has the same effect as appendChild() for a single element: it becomes the last child inside the target (MDN).

Example 4 — beforebegin Sibling Insert

Insert a new card immediately before an existing card.

JavaScript
const card = document.getElementById("card");
const banner = document.createElement("div");
banner.className = "banner";
banner.textContent = "New banner";

card.insertAdjacentElement("beforebegin", banner);
console.log(card.previousElementSibling === banner); // true
Try It Yourself

How It Works

beforebegin places the new element as a sibling immediately before the target. MDN: requires the target to be in a tree with an element parent.

Example 5 — Return Value Check

Use the returned element reference or detect a failed insert.

JavaScript
const box = document.getElementById("box");
const chip = document.createElement("span");
chip.textContent = "chip";

const inserted = box.insertAdjacentElement("beforeend", chip);

if (inserted) {
  console.log("inserted:", inserted.textContent);
} else {
  console.log("insertion failed");
}
Try It Yourself

How It Works

MDN: the method returns the inserted element or null on failure. Store the return value when you need a reference right away.

🚀 Common Use Cases

  • Inserting items before/after a selected list row (MDN demo pattern).
  • Prepending toolbar buttons with afterbegin.
  • Appending messages to a chat panel with beforeend.
  • Placing banners or alerts as siblings with beforebegin.
  • Building dynamic forms without innerHTML strings.
  • Moving existing elements to precise positions in the DOM tree.

🧠 How insertAdjacentElement() Inserts Nodes

1

Create or select element

const node = document.createElement("div")

Element
2

Choose position string

beforebegin, afterbegin, beforeend, or afterend (MDN).

Position
3

Insert into tree

target.insertAdjacentElement(position, node)

DOM
4

Return inserted node

Returns the element on success, or null if insertion failed (MDN).

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available, April 2018).
  • Position strings are matched case-insensitively (MDN).
  • Returns the inserted element, or null on failure (MDN).
  • beforebegin and afterend need an element parent in the tree (MDN).
  • Throws SyntaxError for unknown position; TypeError for invalid element (MDN).
  • Related: append(), before(), after(), insertAdjacentHTML(), JavaScript hub.

Browser Support

Element.insertAdjacentElement() 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.insertAdjacentElement()

Insert an element at beforebegin, afterbegin, beforeend, or afterend — returns the node or null.

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
insertAdjacentElement() Excellent

Bottom line: Use insertAdjacentElement() when you need precise placement of Element nodes. For HTML strings, use insertAdjacentHTML().

Conclusion

Element.insertAdjacentElement() inserts an element node at one of four positions around a target element. It is ideal when you need precise DOM placement without parsing HTML strings.

Continue with append(), before(), after(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use the MDN four-position diagram to pick the right slot
  • Create elements with createElement before inserting
  • Check the return value when insertion might fail
  • Prefer this over HTML strings when building nodes in JS
  • Use beforeend for append-like behavior inside a container

❌ Don’t

  • Pass HTML strings (use insertAdjacentHTML instead)
  • Use invalid position spellings (throws SyntaxError)
  • Assume beforebegin works without a parent element
  • Forget that moving an existing node removes it from its old parent
  • Confuse afterbegin with beforebegin

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.insertAdjacentElement()

Precise element insertion positions.

5
Core concepts
📄 02

Args

pos + el

Two
📄 03

Inside

begin/end

Child
04

Outside

sibling

Peer
05

Null

on fail

Check

❓ Frequently Asked Questions

It inserts a given element node at a position relative to the element it is called on. MDN positions: beforebegin, afterbegin, beforeend, afterend.
No. MDN marks Element.insertAdjacentElement() as Baseline Widely available (across browsers since April 2018). It is not Deprecated, Experimental, or Non-standard.
beforebegin (before the element), afterbegin (first child inside), beforeend (last child inside), afterend (after the element). Matching is case-insensitive (MDN).
The element that was inserted, or null if insertion failed (MDN).
insertAdjacentElement() takes an Element node. insertAdjacentHTML() parses an HTML string into nodes.
MDN: they work only when the node is in a tree and has an element parent.
Did you know?

MDN: beforebegin and afterend insert outside the element as siblings, while afterbegin and beforeend insert as the first or last child inside the element.

More Element Topics

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

insertAdjacentHTML() →

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