In my current project, I am faced with the task of removing various DOM elements from the page. This includes scenarios where I need to remove a single element as well as cases where I need to remove a collection of elements such as a NodeList or an HTMLCollection. To simplify my code and make it more efficient, I wanted to create a single function that could handle both situations.
This led me to come up with the following function:
function removeElement(element) {
if (element instanceof NodeList || element instanceof HTMLCollection) {
// When dealing with a NodeList or HTMLCollection, iterate over each element and remove them
element.forEach(e => e.remove());
} else {
// For a single DOM element, directly call the remove() method on it
element.remove();
}
}
I set out to create a versatile function capable of handling the removal of single DOM elements and collections of elements (NodeList or HTMLCollection). The end result was this function:
Javascript
function removeElement(element) {
if (element instanceof NodeList || element instanceof HTMLCollection) {
// If the element is a NodeList or HTMLCollection, iterate over its elements and remove each one
element.forEach(e => e.remove());
} else {
// Assume it's a single DOM element and directly call remove() on it
element.remove();
}
}
My goal was for this function to be adaptable to different scenarios in my project where I needed to remove elements from the DOM. It was important to have a single, reliable function that could handle both single element removal and multiple element removal effortlessly.
Example Use Cases:
// Removing a single element
const singleElement = document.querySelector('#singleElement');
removeElement(singleElement);
// Removing multiple elements
const multipleElements = document.querySelectorAll('.multipleElements');
removeElement(multipleElements);