patternjavascriptCritical
Remove element by id
Viewed 0 times
elementremovestackoverflow
Problem
When removing an element with standard JavaScript, you must go to its parent first:
Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?
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
Update 2011
This was added to the DOM spec back in 2011, so you can just use:
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
As of DOM4, a helper function is provided to do the same thing:
If you need to support older browsers, you can:
This was added to the DOM spec back in 2011, so you can just use:
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
- Modify the native DOM functions, as in Johan Dettmar's answer, or
- Use a DOM4 polyfill.
Context
Stack Overflow Q#3387427, score: 146
Revisions (0)
No revisions yet.