JSFiddle - React, Tailwind, and code Playground
HTML
<div id="content-body" class="clearfix">
<!-- detail div no 1 = 3 items inside -->
<span class="countDiv0"></span>
<div class="detail">
<div class="box">
Div item 1
</div>
<div class="box">
Div item 2
</div>
<div class="box">
Div item 3
</div>
</div>
<br /><br />
<!-- detail div no 1 = 4 items inside -->
<span class="countDiv1"></span>
<div class="detail">
<div class="box">
Div item 1
</div>
<div class="box">
Div item 2
</div>
<div class="box">
Div item 3
</div>
<div class="box">
Div item 4
</div>
</div>
</div>
<button id="add-new">
Add
</button>
JavaScript
$('.detail').each(function(i) {
const targetNode = this;
const countingDiv = $('.countDiv' + i);
countingDiv.text(
`There are ${
$(targetNode).children('.box').length
} divs inside parent box detail.`
);
createObserver(targetNode);
});
$('#add-new').click(function() {
$('.detail').append('<div class="box">new new</div>')
})
function createObserver(targetNode) {
const config = { childList: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
for (var mutation of mutationsList) {
if (mutation.type == 'childList') {
countingDiv.text(
`There are ${
$(targetNode).children('.box').length
} divs inside parent box detail.`
);
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
}