JavaScript remove() doesn't work in IE

Viewed 68689

I have the following code in JavaScript:

all_el_ul = document.getElementsByClassName('element_list')[0];
div_list = all_el_ul.getElementsByTagName("div");
for (i = 0; i < div_list.length; i += 1) {         
  div_list[i].remove();             
}

I know that this is the problem because I used alert('test'); to see where the code stops working. Everything is working in FF, Chrome, Opera and others but not in IE.

Could you please tell what is wrong?

5 Answers

Try adding this to the top of your JavaScript file:

if (!('remove' in Element.prototype)) {
  Element.prototype['remove'] = function () {
    if (this.parentNode) {
      this.parentNode.removeChild(this);
    }
  };
}

It is a small Element.remove() polyfill.

Add that to your JS and [element].remove() should magically start working in IE.

Please try this. (Support all browsers)

var child = document.getElementById(id);
child.parentNode.removeChild(child);
Related