π Prefer childNode.remove() over parentNode.removeChild(childNode).
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π§π‘ This rule is automatically fixable by the --fix CLI option and manually fixable by editor suggestions.
Node#remove() is a cleaner and more direct way to remove an element from the DOM. It's simpler, more readable, and doesn't require a reference to the parent node.
The autofix does not preserve the error that parent.removeChild(child) throws when child is not a child of parent. When evaluating the parent can have side effects, such as a call, the rule offers a suggestion instead.
// β - Requires knowing the parent and using the indirect method
const element = document.querySelector('.banner');
element.parentNode.removeChild(element);
// β
- Direct, straightforward removal
const element = document.querySelector('.banner');
element.remove();// β
const button = document.getElementById('close-btn');
button.parentNode.removeChild(button);
// β
const button = document.getElementById('close-btn');
button.remove();// β
class Modal {
close() {
this.parentNode.removeChild(this);
}
}
// β
class Modal {
close() {
this.remove();
}
}