Zaz Zaz - 6 months ago 10
Javascript Question

Remove element by id

When removing an element with standard JavaScript, you must go to it's parent first:

var element = document.getElementById("element-id");
element.parentNode.removeChild(element);


Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?

Zaz Zaz
Answer

The DOM is organized in a tree of nodes, where each node has a value, along with a list of references to its child nodes. So element.parentNode.removeChild(element) mimics exactly what is happening internally: First you go the the parent node, then remove the reference to the child node.

As of DOM4, a helper function is provided to do the same thing: element.remove(). This works in WebKit and Firefox, but not IE. If you need to support older browsers, you can:

Comments