Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Element.after() — inserting siblings after an element

Element.after inserts nodes and text as siblings, normally immediately after the element. It does not add children to that element.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

element.after(...nodes)

Element.after is an instance method supplied by the ChildNode mixin in the DOM standard, not ECMAScript. If the element has a parent, element.after(...nodes) normally inserts nodes and text immediately after it. However, preparing the nodes for insertion can move the element itself, even if it is not passed directly as an argument. If a is the sole child of a DocumentFragment named f and b is a separate element, a.after(b, f) moves a out of f and places it after b, then inserts both into f in the order b, a. If the element itself is passed, its position in the argument list matters: given two distinct sibling elements a and b, a.after(b, a) places b immediately before a.

Strings become Text nodes without HTML parsing. Existing nodes are moved, not copied. The method returns undefined; if the element has no parent, it inserts nothing. The parent need not be connected to the document.

An invalid tree hierarchy causes HierarchyRequestError. Unlike append(), after() does not insert children into its receiver. This is a DOM environment API: the Node.js version alone does not establish its availability.

Examples

const parent = document.createElement('div');
const first = document.createElement('span');
first.textContent = 'A';
const last = document.createElement('span');
last.textContent = 'C';
parent.append(first, last);

const middle = document.createElement('strong');
middle.textContent = 'B';
const result = first.after(' / ', middle);

console.log(parent.textContent);
console.log(first.nextSibling.nodeType === Node.TEXT_NODE);
console.log(middle.nextSibling === last);
console.log(result === undefined);

Result

A / BC
true
true
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources