Listen DomInsert event.

by MaxenceBrasselet

HTML

<div class="container">
    <div><p>element 1</p></div>
</div>
<button id="insertToContainer">Insert in container</button>

JavaScript

var DomNodeInsertCallback =  function (e) {
     console.log("Element added to container");
     
     wrapMyElement(e.target);
 }

$('body').on('DOMNodeInserted', '.container', DomNodeInsertCallback);

function wrapMyElement(element) {
    //Need to disable event because it cause an infinite loop.
    //.wrap cause an infinite loop because it insert content into the body so it calls and calls again the event.
    //Comment it and the following on to see the loop.
    $('body').off('DOMNodeInserted', '.container');
    
    $(element).wrap('<div style="border: 1px solid red;"></div>');
    
    //Then you can enable it again, because you have inserted your content.
    //Comment it and the previous off to see the loop.
    $('body').on('DOMNodeInserted', '.container', DomNodeInsertCallback);
}

$('#insertToContainer').on('click', function() {
   $('.container').append('<p>New element</p>');
});