JAVASCRIPT
Remove an Element from the DOM by ID or Selector
Discover how to efficiently remove an HTML element from the Document Object Model (DOM) using its unique ID or a CSS selector in JavaScript.
function removeElement(selector) {
const elementToRemove = document.querySelector(selector);
if (elementToRemove) {
elementToRemove.remove(); // Modern and simpler way
console.log(`Element matching '${selector}' removed.`);
} else {
console.warn(`Element matching '${selector}' not found.`);
}
}
// Example Usage:
// Assuming you have an element like <div id="old-div">...</div>
removeElement('#old-div');
// Or for the first element with a specific class:
// <span class="removable-item">Item 1</span>
// <span class="removable-item">Item 2</span>
removeElement('.removable-item');
How it works: This snippet provides a straightforward way to remove an element from the DOM. The `removeElement` function takes a CSS selector as an argument. It uses `document.querySelector()` to find the first matching element. If the element exists, `elementToRemove.remove()` is called to detach it from its parent. This method is concise and widely supported, offering a clean way to clear elements from the page, for instance, when a user closes a modal or deletes an item from a list.