A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

[Proposal] `Node.insertAfter`


Link: Suggestion: `Node.insertAfter(newNode, referenceNode)` · Issue #986 · whatwg/dom · GitHub

In frameworks, it’s far more common to want to insert after the current node than before the next node, and it’s significantly easier to implement. Problem is, for performance reasons, some of us employ various hacks like this (example call) to avoid having to pay the cost of a C++ round trip just to get the next sibling of a given DOM node.

I also see a gaping hole in this matrix for child-relative operations:

Operation Node method ChildNode method jQuery method
Insert before node.insertBefore(child, ref) child.before(...nodes) $(parent).before(child), $(child).insertBefore(parent)
Insert after child.after(...nodes) $(parent).after(child), $(child).insertAfter(parent)
Remove node.removeChild(child) child.remove() $(child).remove()
Replace node.replaceChild(child, prev) child.replaceWith(...nodes) $(child).replaceWith(newChild), $(newChild).replaceAll(child)

I propose we fill that with the following method:

partial interface Node {
    [CEReactions] Node insertAfter(Node node, Node? child);

The semantics are pretty obvious:

  • If child is null, this prepends node as the first child.
  • If child is not null, this inserts node after child similar to how insertBefore inserts it before child.

I explain at length in the issue why child.after isn’t appropriate for all use cases.