JS DOM API for Beginners: Removing all elements with a certain class
Michael Puckett
Posted on January 19, 2020
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.
🤟
Posted on January 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024