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?
From inside your component:
document.body.insertBefore(this, document.body.firstChild);
// or, for evergreen browsers, if you don't care about IE:
document.body.prepend(this);
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);
// or, for evergreen browsers, if you don't care about IE:
document.body.prepend(document.querySelector('page-alert'));