Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!