Alternative of document.getElementsByTagName('body') in angular 2/5/6

1.7k Views Asked by At

I want to get the 'body' element form the other child component.
How can I get the body element form the child component?
As I want to append and remove the class to body form child component.

1

There are 1 best solutions below

0
On BEST ANSWER

I can suggest a workaround where you can traverse back until you get body element. And you could use Renderer2 so that code can work smoothely with server side rendering as well.

getParentNode (node) {
     //make sure you inject Render2 inside constructor.
     return this.renderer.parentNode(node);
}

getBodyElement (element) {
    let currentElement = element;
    // below can be optimised to have single `getParentNode` method call.
    while(this.getParentNode(currentElement)&& this.getParentNode(currentElement).nodeName != 'HTML'){
      currentElement = this.getParentNode(currentElement)
    }
    return currentElement
}

ngOnit() {
   let bodyElement = this.getBodyElement(this.elementRef.nativeElement)
}