Ways to eliminate several DOM elements at once with a single JavaScript function

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);

Answer №1

Both an HTMLCollection and a NodeList adhere to an array-like interface, unlike an element.

This distinction can be useful to identify the type of value for iterating through and removing items in the collection or removing a single element. An example is provided below that demonstrates using this approach as advised by MDN:

The HTMLCollection within the HTML DOM is live; it updates automatically when changes are made to the underlying document. It's recommended to create a copy (e.g., using Array.from) before iteration if nodes are being added, moved, or removed.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection

The function remove, described below:

  • If the value is falsy (such as a null result from the querySelector API), the function returns early; otherwise...
  • If the value has a property length, indicating it's array-like, the items are first collected into a static array before being iterated over for removal; else...
  • The remove method of the value is called.

Feel free to click on the "Run code snippet" button to reload the demo and experiment with different button orders.

function remove(removable) {
  if (!removable) return;
  if ("length" in removable) {
    for (const element of Array.from(removable)) element.remove();
  } else removable.remove();
}

// Removing a single element
document.getElementById("removeSingle").addEventListener("click", () => {
  const singleElement = document.querySelector("#singleElement");
  remove(singleElement);
});

// Removing multiple elements
document.getElementById("removeMultipleNL").addEventListener("click", () => {
  const nodeList = document.querySelectorAll(".multipleElements");
  remove(nodeList);
});

document.getElementById("removeMultipleHC").addEventListener("click", () => {
  const htmlCollection = document.getElementsByClassName("multipleElements");
  remove(htmlCollection);
});
body { font-family: sans-serif; }
#singleElement { color: red; }
.multipleElements { color: blue; }
<div>
  <button id="removeSingle">Remove single</button>
  <button id="removeMultipleNL">Remove multiple as NodeList</button>
  <button id="removeMultipleHC">Remove multiple as HTMLCollection</button>
  <div id="singleElement">single</div>
  <div class="multipleElements">multiple</div>
  <div class="multipleElements">multiple</div>
</div>

Code in the TypeScript Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My goal is to develop a program that generates a tree structure from an array of objects

I am looking to transform an array of objects by renaming specific keys and removing certain key-value pairs at each level. Here is the initial input: { "node": [ { "nodeName": "Clothes", "nodePath&qu ...

Passing form values from JavaScript to a JSP page - a comprehensive guide

I am working on a sample HTML page that includes inline JavaScript for calculating geocodes and retrieving latitude and longitude values. My question is, how can I submit all the form values along with the latitude and longitude returned from the showlocat ...

Upon adding data to mongodb, an error message is displayed stating "Cannot read property '_id' of undefined."

Backend Server-Side Code The following is my server-side code. Below it, you can find the client-side code along with the error that is being displayed. I am having trouble identifying what the issue might be. app.post("/service", async (res, re ...

Working with Closure in Node.js

After encountering issues with nested for loops, I decided to explore closures as an alternative solution. Below is the basic structure of my previous code: // First for loop for(data) { connection.query(records as per data) if(!error) { ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

connecting with Google Analytics

We are looking to incorporate Google Analytics into a sizable .NET website. The website utilizes multiple master pages (4 or 5), so the plan was to insert the necessary JavaScript code into each master page. <script type="text/javascript">//<![CD ...

What is the best way to initiate a slideshow using an external .js file?

Having an issue with my slideshow. When I put the CSS and JavaScript code in the same page, it kind of "works" but quickly goes transparent, which is not ideal for me. I prefer keeping things organized with separate files - one for each. However, when I mo ...

The value from select2 dropdown does not get populated in my article in Angular

I am attempting to link the selected value in a dropdown menu to an article, with a property that matches the type of the dropdown's data source. However, despite logging my article object, the property intended to hold the selected dropdown value app ...

angular-ui-tab-scroll: Odd spacing between blocks and tabs, each separated individually

Greetings! I would like to express my gratitude for this wonderful library! However, I am encountering an unusual issue when trying to wrap a tabset with tabs that are included separately. This can be done either by adding individual tab elements manually ...

Can a single button click be shared across multiple forms?

The main concept involves a grid where when a user double-clicks on a row, a modal window (Bootstrap panel) opens with a panel-body section for editing the data and a panel-footer containing a btn-group for actions like "Save", "Cancel", or "Close". This s ...

Setting up and customizing Express with Angular

Currently working on a straightforward Angular/Express todo-list app, I encountered some difficulties. As the project is still in progress, after running the code on localhost:3000, I noticed that {{ thing }} was displayed literally on the webpage. The di ...

The result after calling JSON.parse(...) was not accurate

The following method is used in the controller: @RequestMapping(value = "channelIntentionDetails.html", method = RequestMethod.POST) public @ResponseBody Report getChannelIntentionDetails(@RequestBody SearchParameters searchParameters) { LOGGER.in ...

Issue with Vue.js 2.0 transition not triggering on changing routes dynamically

I've encountered an issue where transitions are not firing on dynamic routes with parameters. For example, when navigating from /chapter/1 to /chapter/2, no transition occurs. However, when going from /chapter/1 to /profile/1, a transition does occur! ...

Is there a way to convert arrow functions in vue files through transpilation?

I have developed a Vue application that needs to function properly in an ES5 browser (specifically iOS 9). One issue I've encountered is that some of the functions within the Vue components are being transformed into Arrow functions: ()=>, which i ...

Steps to verify multiple v-for loops and apply style if both are present

<div v-for="memberMembershipyear in memberMembershipyears"> <li v-for="membershipYear in membershipYears" :style="membershipYear.num === memberMembershipyear.num ? 'color:green' : color:red'"> {{membershipYear.me ...

Struggling to target the child elements of an unordered list with jQuery?

Need help with selecting the children of a list item in a jQuery mobile navigation? I am having some trouble with this task. Here is a fiddle demonstrating what I have done so far: http://jsfiddle.net/jhrz9/ <div data-role="panel" id="left-panel" data ...

Responsive design in Android does not function as intended

My goal is to create a responsive design for my website, but I am encountering issues with importing the CSS files into the HTML. When I try to view the site in both the Windows version of Chrome and the Android version, all I see is a white screen. I am c ...

You can generate a TBODY element by utilizing an Array

I have an array with the following structure. https://i.sstatic.net/5AdO9.png below is the code I am using success: function(data) { data = $.parseJSON(data); for (i = 0; i < data.length; i++) { con ...

obtain every drop-down choice from Angular 2's selectiongetConfig() function

Within the document, there is a select element as shown below: <select tabindex="1" size="5" name="abc" multiple> <option value>Select a value.</option> <option value>option 1</option> <option value>option 2 ...

Is the size of the JSON file inhibiting successful parsing?

After retrieving a large list of schools with their respective columns from the database, totaling over 1000 rows, I converted it to JSON and passed it to my view. I then attempted to parse it using $.parseJSON('@Html.Raw(Model.subChoiceJsonString)& ...