'Express item.parentElement.remove() in a way that is supported by IE

From what I understand, the

remove()

function is not supported in IE. I have a JS function that creates a div and appends it to an existing list.The div contains another div styled as a button (this is the 'item' in the title, that's what I called it when I got it from HTML), which, on click, removes its parentNode (and consequently itself) from the DOM (by means of remove()), though it still 'exists' in that JavaScript can read it's data and stuff. I need a way to remove it from the DOM, as well as all of it's child elements. Setting it's innerHTML equal to nothing will not work, nor will setting it's display to none. Any idea how to do this in a way compatible with IE?

Any help appreciated, please no jQuery or other frameworks.



Solution 1:[1]

Anytime you would use .remove(), you can always just use .removeChild() instead with slightly different code around it.

So, if you wanted to do to remove the parent of a given node:

item.parentElement.remove();

Then, you can instead do this:

var p = item.parentNode;
p.parentNode.removeChild(p);

If you want to put this in a utility function, you can do this:

function removeNode(node) {
    node.parentNode.removechild(node);
}

And, in your case, instead of item.parentElement.remove() you would call it like this:

removeNode(item.parentNode);

Note, I'm using parentNode instead of parentElement since you appear to want IE compatibility with older versions of IE. parentNode and parentElement are not exactly the same, but it's very rare where parentNode would be different than parentElement (in fact, I can't think of a case in a normal DOM where it wouldn't be appropriate to use parentNode). See Difference between DOM parentNode and parentElement for a discussion of the differences.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community