DEV Community

Michael Puckett
Michael Puckett

Posted on

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.

🤟

Top comments (1)

Collapse
 
rossangus profile image
Ross Angus

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