# 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()`.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

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

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 4} */}
```js
list.insertBefore(item, marker);
list.replaceChild(item, placeholder);
heading.insertAdjacentText("beforeend", "!");
heading.insertAdjacentElement("afterend", note);
```

Not reported:

{/* good */}
```js
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:

{/* good */}
```js
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.
