Remove element by ID
Delete a specific DOM element by its ID using this script:
Element removal in modern browsers
Handling DOM manipulation in contemporary browsers is a breeze, especially with Node.remove()
in our arsenal. This protocol phased out redundant approaches such as finding the parent node prior to removal. Conveniently, this method is adopted by both NodeList
and HTMLCollection
objects in present-day browsers.
Always bear in mind that legacy browsers, particularly Internet Explorer versions 11 and below, do not natively support Node.remove()
. Here’s a viable solution using outerHTML
in such cases:
This outerHTML
tempering though, might have unintentional aftermath on neighbouring elements. As a robust fallback for all browsers, the time-tested approach of parentNode.removeChild(childNode)
can still be employed:
Achieving universality in element removal
In cases where we are expected to support a wide range of browsers, even those harking back to the IE7 era, a polyfill or custom method can be used to beautify the native prototypes:
Despite it often being frowned upon to modify native prototypes due to potential collisions with future standards, doing so can provide wide-ranging support when required.
Taking a deep dive: nuances of removing elements
When deleting DOM elements, side effects should be anticipated and managed. Removing an element which has event listeners attached might lead to memory leaks without appropriate cleanup:
The Node.removeChild() method offers more surgical control when removing elements:
It is also beneficial to understand and handle potential errors when an element does not exist:
In addition, when using getElementsByClassName
or getElementsByTagName
to obtain a NodeList
, remember these collections are live. Removing an element impacts the collection:
Was this article helpful?