nodeModificationMethods
Prefer modern DOM APIs like .replaceWith() and .before() over legacy methods like .replaceChild() and .insertBefore().
✅ This rule is included in the browser logical preset.
Modern DOM APIs provide simpler and more intuitive ways to modify the DOM compared to their legacy counterparts. These newer methods can be called directly on the node being modified, accept multiple nodes or strings at once, and do not require traversing to parent nodes. This rule enforces calling to modern APIs over their legacy equivalents.
Examples
Section titled “Examples”element.insertAdjacentElement("afterend", newNode);parentNode.replaceChild(newNode, oldNode);parentNode.insertBefore(newNode, referenceNode);referenceNode.insertAdjacentText("beforebegin", "text");element.after(newNode);oldNode.replaceWith(newNode);referenceNode.before(newNode);referenceNode.before("text");Details
Section titled “Details”This rule enforces the use of modern DOM manipulation methods:
childNode.replaceWith(newNode)instead ofparentNode.replaceChild(newNode, oldNode)referenceNode.before(newNode)instead ofparentNode.insertBefore(newNode, referenceNode)referenceNode.before('text')instead ofreferenceNode.insertAdjacentText('beforebegin', 'text')referenceNode.prepend('text')instead ofreferenceNode.insertAdjacentText('afterbegin', 'text')referenceNode.append('text')instead ofreferenceNode.insertAdjacentText('beforeend', 'text')referenceNode.after('text')instead ofreferenceNode.insertAdjacentText('afterend', 'text')referenceNode.before(newNode)instead ofreferenceNode.insertAdjacentElement('beforebegin', newNode)referenceNode.prepend(newNode)instead ofreferenceNode.insertAdjacentElement('afterbegin', newNode)referenceNode.append(newNode)instead ofreferenceNode.insertAdjacentElement('beforeend', newNode)referenceNode.after(newNode)instead ofreferenceNode.insertAdjacentElement('afterend', newNode)
Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you need to support older browsers that do not have these modern DOM APIs, you might need to continue using the legacy methods or use polyfills.
Further Reading
Section titled “Further Reading”- MDN: ChildNode.replaceWith()
- MDN: ChildNode.before()
- MDN: ChildNode.after()
- MDN: Element.append()
- MDN: Element.prepend()
Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- ESLint:
unicorn/prefer-modern-dom-apis - Oxlint:
unicorn/prefer-modern-dom-apis
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.