Wait for a "3rd party" element to be appended to the DOM Let's say we're writing a user script which interacts with a 3rd party site we don't control. We want to open a menu, so we trigger a click on the button and then wait 10ms before accessing the menu (which is appended to the document after the click), like this:

$button = $('#button');
$button.trigger('click');
setTimeout(function() {
    //access the menu
}, 10);


This works, because it takes less than 10ms for the 3rd party site's handler to appended the menu to the DOM once the button is clicked. But it feels like bad code. Is there a better way to write this?
That's a perfect job for MutationObserver.

new MutationObserver(function(mutations) {
    this.disconnect();
    // access the menu
    ........
}).observe($('.immediate-parent-of-the-menu')[0], {childList: true});

$button = $('#button');
$button.trigger('click');


The simplest case above works as-is if the menu is added in one mutation, otherwise you'd have to check each of the mutations array elements for addedNodes.