Skip to content
NewBun 1.4.5 is out. Release notes
AphrodyBun

Linter · Rules

unicorn/prefer-modern-dom-apis

Require .before(), .after(), .append(), .prepend() and .replaceWith() over older DOM methods

insertBefore() and replaceChild() need the parent of the node you care about, and it's easy to mix up the order of their arguments. insertAdjacentText() and insertAdjacentElement() take the position as a string. You call the newer methods on the node itself, and they're named after what they do.

ReportedWrite instead
parent.insertBefore(node, reference)reference.before(node)
parent.replaceChild(node, old)old.replaceWith(node)
element.insertAdjacentText("beforebegin", text)element.before(text)
element.insertAdjacentText("afterbegin", text)element.prepend(text)
element.insertAdjacentText("beforeend", text)element.append(text)
element.insertAdjacentText("afterend", text)element.after(text)

insertAdjacentElement() is treated like insertAdjacentText().

Configure

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"unicorn/prefer-modern-dom-apis" = "error" # or "warn"

Examples

Reported:

list.insertBefore(item, marker);
list.replaceChild(item, placeholder);
heading.insertAdjacentText("beforeend", "!");
heading.insertAdjacentElement("afterend", note);

Not reported:

marker.before(item);
placeholder.replaceWith(item);
heading.append("!");
heading.after(note);

insertBefore() and replaceChild() are only reported when they're called on a plain variable:

document.body.insertBefore(banner, main);

When not to use it

insertBefore(), replaceChild() and insertAdjacentElement() return a node, and the newer methods return undefined. A call is reported even if you use its result, and in that case it needs more than a rename.