Prefer .before()
over .insertBefore()
, .replaceWith()
over .replaceChild()
, prefer one of .before()
, .after()
, .append()
or .prepend()
over insertAdjacentText()
and insertAdjacentElement()
💼 This rule is enabled in the ✅ recommended
config.
🔧 This rule is automatically fixable by the --fix
CLI option.
Enforces the use of:
- childNode.replaceWith(newNode) over parentNode.replaceChild(newNode, oldNode)
- referenceNode.before(newNode) over parentNode.insertBefore(newNode, referenceNode)
- referenceNode.before('text') over referenceNode.insertAdjacentText('beforebegin', 'text')
- referenceNode.before(newNode) over referenceNode.insertAdjacentElement('beforebegin', newNode)
There are some advantages of using the newer DOM APIs, like:
- Traversing to the parent node is not necessary.
- Appending multiple nodes at once.
- Both
DOMString
and DOM node objects can be manipulated.
foo.replaceChild(baz, bar);
foo.insertBefore(baz, bar);
foo.insertAdjacentText('position', bar);
foo.insertAdjacentElement('position', bar);
foo.replaceWith(bar);
foo.replaceWith('bar');
foo.replaceWith(bar, 'baz'));
foo.before(bar)
foo.before('bar')
foo.before(bar, 'baz')
foo.prepend(bar)
foo.prepend('bar')
foo.prepend(bar, 'baz')
foo.append(bar)
foo.append('bar')
foo.append(bar, 'baz')
foo.after(bar)
foo.after('bar')
foo.after(bar, 'baz')