[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.

JavaScript

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

That’s all from the Gemba.