Skip to content

Latest commit

Β 

History

History
52 lines (39 loc) Β· 1.69 KB

prefer-dom-node-remove.md

File metadata and controls

52 lines (39 loc) Β· 1.69 KB

prefer-dom-node-remove

πŸ“ 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.

Examples

// ❌ - 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();
	}
}