Kamel Mili
Kamel Mili

Reputation: 1434

Detect length div after append

I'm having trouble detecting length and index of the appended div, I dug through a lot of things, and there's a solution with MutationObservers but somehow I'm continuously asking myself do I need it for this kind of problem,

However, let's get to the issue. I have a div populated dynamically structured like this,

<div class="array-placeholder">
   <div id="tagContainer" class="row tag">

     <!-- dynamic elements -->.....

   </div>
</div>

when I click to this button it appends another dynamic element, see the code below :

 $('body').off('click.addCollection').on('click.addCollection', function () {

 //list and new widgets are just containers and datalist inside the array-placeholder div  
 let newElem = $(list.attr('data-widget-tags')).html(newWidget);
    newElem.appendTo(list);

 })

I've tried this solution to get the length of the array-placeholder div but it doesn't seem to work, the function is never launched:

$('body').on('DOMSubtreeModified', '.array-placeholder', function (event) {
    console.log( $(".array-placeholder > div").length);
})

result

//nothing and when you click to the appended element via moveUpButton.closest(".tag")  you 0 as index  

do I have to implement MutationObserver to solve this if yes, could you guide me through this, thanks

Upvotes: 1

Views: 953

Answers (2)

Ivica Pesovski
Ivica Pesovski

Reputation: 847

You can get all children using jquery's find('*') and then count their length;

$(".array-placeholder").find('*').length;

Or if you want only divs then do:

$(".array-placeholder").find('div').length;

Upvotes: 1

Mamun
Mamun

Reputation: 68923

DOMSubtreeModified

This event has been deprecated in favor of the Mutation Observer API

Yes you have to use Mutation Observer API. To implement that you can refer This

Upvotes: 2

Related Questions