Remove element by id
Posted By: Josh
When removing an element with standard JavaScript, you must go to its 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?
Solution
element.remove()
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 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 96% of browsers (as of 2020), but not IE 11. If you need to support older browsers, you can:
- Remove elements via the parent node, as in the question,
- modify the native DOM functions, as in Johan Dettmar’s answer, or
- use a DOM4 polyfill.
Answered By: Anonymous
Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.