0

I want to do the automatic initialization when dom was inserted, I know there are several ways, but is that passable to do it like event listening on jQuery

In the past, we can do something like

HTML

<button id="btn_add">add</button>
<div class="container"></div>

JS

$('#btn_add').on('click', function() {
    var html = $('<div class="new"></div>');

    $('.container').append(html);

});

$('.container').on('DOMNodeInserted', '.new', function() {
    $(this).html('new content');
});

But DOMNodeInserted was deprecated, We can do something like

$('#btn_add').on('click', function() {
    var html = $('<div class="new"></div>');

    $('.container').append(html).find('.new:last').trigger('created');

});

$('.container').on('created', '.new', function() {
    $(this).html('new content');
});

or

$('#btn_add').on('click', function() {
    var html = $('<div class="new"></div>');

    $('.container').append(html);

    doInit();
});

function doInit() {
    $('.container').find('.new:last').html('new content');
}

But it's not as beautiful as listen DOMNodeInserted, any better writing style?

trincot
  • 317,000
  • 35
  • 244
  • 286
Chan
  • 1,947
  • 6
  • 25
  • 37
  • 4
    There is the `mutationObserver` api: https://developer.mozilla.org/es/docs/Web/API/MutationObserver – Josué Zatarain Jan 18 '17 at 14:56
  • Possible duplicate of [Event when element added to page](http://stackoverflow.com/questions/7434685/event-when-element-added-to-page) – trincot Jan 18 '17 at 15:04
  • Also see [Can jQuery selectors be used with DOM mutation observers?](http://stackoverflow.com/questions/12596231/) – Ritesh Jan 18 '17 at 15:09
  • @JosuéZatarain I know this one, but it's only support IE11 – Chan Jan 18 '17 at 17:35

0 Answers0