<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>');
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.