Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

58
Vistas
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?

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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'));
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos