Blog>
Snippets

Removing Elements from the DOM

Provide an example of how to remove an element from the DOM using Renderer2's removeChild method.
import { Renderer2 } from '@angular/core';

// constructor(private renderer: Renderer2) {}

function removeElement(renderer: Renderer2, parent: any, child: any) {
    // Make sure both the parent and child elements are defined
    if (parent && child && child.parentNode === parent) {
        // Use the Renderer2 service to remove the child from the parent
        renderer.removeChild(parent, child);
    }
}
This code defines a function that accepts a Renderer2 instance, the parent DOM element, and the child DOM element to be removed. It first checks if both elements are defined and if the child's parent node is indeed the provided parent. If so, it uses Renderer2's removeChild method to remove the child element from the DOM.