DEV Community

Michael Puckett
Michael Puckett

Posted on

1

JS DOM API for Beginners: Removing all elements with a certain class

If you're familiar with CSS 🎨, then you can use the same selector syntax to target all matching elements in JavaScript 💻.

window.document.querySelectorAll('.box')

Notice the selector is the same in CSS, representing elements with a box class.

This returns a special kind of array-like object for DOM elements called a NodeList.

What if we wanted to remove all the elements with a box class?

One way is to call .remove() on each of the elements. To do this, we need to loop over each element.

NodeLists aren't technically arrays, so they don't have a .forEach() method 😫 but they are iterable, meaning they can be converted to regular arrays 🤓

Here's the syntax for the conversion:

[...window.document.querySelectorAll('.box')]

Now we can use .forEach() to remove each item:

[...window.document.querySelectorAll('.box')].forEach(node => node.remove())

It can be any valid CSS selector, such as .boxes li.box.circle[aria-selected="true"]

You could also use .map() or .reduce() on a list of DOM elements this way.

🤟

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (1)

Collapse
 
rossangus profile image
Ross Angus

Lovely work, Michael. I literally first encountered this last week. That "ellipsis" syntax is weird.

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay