How to remove all elements of a certain class from the DOM?
[].forEach.call(document.querySelectorAll('.hi'),function(e){
e.parentNode.removeChild(e);
});
Here I'm using Array.prototype.forEach
to easily traverse all elements in an array-like object, i.e. the static NodeList returned by querySelectorAll
, and then using removeChild()
to remove the item from the DOM.
For older browsers that don't support querySelectorAll()
or forEach()
:
var classMatcher = /(?:^|\s)hi(?:\s|$)/;
var els = document.getElementsByTagName('*');
for (var i=els.length;i--;){
if (classMatcher.test(els[i].className)){
els[i].parentNode.removeChild(els[i]);
}
}
Note that because getElementsByTagName
returns a live NodeList, you must iterate over the items from back to front while removing them from the DOM.
There are also some older browsers that don't support querySelectorAll
but that do support getElementsByClassName
, which you could use for increased performance and reduced code.
To remove an element you do this:
el.parentNode.removeChild(el);
MDN is a great reference. Here are a few relevant pages:
Node
parentNode
removeChild
However you'll run into issues if you loop like that since getElementsByClassName returns a live list, when you remove a node the element is removed from the list as well so you shouldn't increment or you will end up skipping every other element. Instead just continually remove the first element in the list, until there is no first element:
var paras = document.getElementsByClassName('hi');
while(paras[0]) {
paras[0].parentNode.removeChild(paras[0]);
}
IMO jQuery is great at showing you what is possible to do in Javascript. I actually recommend that after about a week or two of plain JS you learn jQuery, get good at it, and remember what it's abstracting away. One day when you have an excellent grasp of Javascript scoping, objects, and such which you can obtain while using jQuery, go back and try learning how to interact better with the DOM without a library. That way you'll have an easier time learning plain JS and you'll appreciate the abstraction that libraries can provide you even more, while learning that when you only need one or two things a library provides you may be able to write them yourself without including the entire library.
Simple ES6 answer:
document.querySelectorAll('.classname').forEach(e => e.remove());
Explanation:
document.querySelectorAll()
loops through the elements in the document returning a NodeList of all elements with the specified selector (e.g.'.class'
,'#id'
,'button'
)forEach()
loops through the NodeList and executes the specified action for each elemente => e.remove()
removes the element from the DOM
Note, however, that this solution is not supported by Internet Explorer. Then again, nothing is.