Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
How to use MutationObserver with AlpineJS and detect when an element is added to the DOM?

I need an external script to add an element the DOM. My Alpine method should react to that change. So inside one of my Alpine methods I added:

const observer = new MutationObserver(() =>{
    const myIframe = document.getElementById('myIframe');
    if (document.contains(myIframe)) {
        this.myIframeIsAvailable = true;
        observer.disconnect();
    }
});
observer.observe(document, { attributes: false, childList: true, characterData: false, subtree: true });

Unfortunately, the observer constructor creates a new scope, so I can't access Alpine's this in there. How can I access this in there?

Initially I thought I could add something like on:childrenHaveChanged to my template, but I can't find a matching event for that.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I must have made a mistake in my original syntax, because now the approach seems to work. Just in case anyone is looking for a solution:

Codepen

document.addEventListener('alpine:init', () => {
    Alpine.data('myApp', () => ({
        elementHasBeenAdded: false,
        
        onClick(){
            const observer = new MutationObserver(() =>{
                const child = document.getElementById('child');
                if (document.contains(child)) {
                    this.elementHasBeenAdded = true;
                    observer.disconnect();
                }
            });
            observer.observe(document, { attributes: false, childList: true, characterData: false, subtree: true });
            
            const parent = document.getElementById('parent');
            let child = document.createElement('div');
            child.id = "child";
            child.innerHTML = "I'm a child";
            parent.appendChild(child);
        },
    }))
});
<div id="parent" x-data="{...myApp()}">
    <p x-ref="paragraph">The value of elementHasBeenAdded is: <code x-text="elementHasBeenAdded">Loading ...</code></p>
    <p>Click here:</p>
    <button x-on:click="onClick()">Start observer</button>
</div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda