[JavaScript] Remove All Elements with Specified ID or Class Name
Tadashi Shigeoka · Sun, February 5, 2017
I’ll introduce methods to remove all elements with specified ID or class name in JavaScript.
This is implemented in pure JavaScript without using jQuery.
Remove Element with Specified ID
var removeIdElement = function(id){
var e = document.getElementById(id);
if (e) {
e.parentNode.removeChild(e);
}
};
Remove All Elements with Specified Class Name
var removeClassElement = function(className){
var elements = document.getElementsByClassName(className);
for (var i = 0; i < elements.length; i++) {
var e = elements[i];
if (e) {
e.parentNode.removeChild(e);
}
}
};
The key point for removing elements is that to remove an element itself, you traverse to the parent node with parentNode and remove the child node with removeChild.
Reference Information
- document.getElementById - Web API Interface | MDN
- document.getElementsByClassName - Web API Interface | MDN
- Node.parentNode - Web API Interface | MDN
- Node.removeChild - Web API Interface | MDN
That’s all from the Gemba.