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.
| Reported | Write 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:
[lint.rules]
"unicorn/prefer-modern-dom-apis" = "error" # or "warn"Examples#
list.insertBeforePrefer using before over insertBefore.(item, marker);
list.replaceChildPrefer using replaceWith over replaceChild.(item, placeholder);
heading.insertAdjacentTextPrefer using append over insertAdjacentText.("beforeend", "!");
heading.insertAdjacentElementPrefer using after over insertAdjacentElement.("afterend", note);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.