Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom Web Component – How can I append it to the beginning of the <body> regardless of where the component is used?

A use case for this is creating a custom page alert component

 <page-alert data-alertHeading='You are in danger' data-alertInfo ="This is a description of why you are in danger.">
 </page-alert>

normally, the templated HTML would be added where the component code was used in the page with:

    this.attachShadow({mode: 'open' });
    this.shadowRoot.appendChild(template.content.cloneNode(true));

I however would like to append this custom component to the body so that it is the very first element following the opening body tag and will always appear at the top of the page. How can I go about accomplishing that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From inside your component:

document.body.insertBefore(this, document.body.firstChild);

From the outside, if your element is already in the DOM but needs to be moved:

document.body.insertBefore(document.querySelector('page-alert'), document.body.firstChild);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading