JoeTidee
JoeTidee

Reputation: 26124

How to automatically react to DOM changes?

I have a list of items in the DOM:

<ul id="my_list">
    <li class="relevant">item 1 <a onclick="remove(1)">Remove</a></li>
    <li class="relevant">item 2 <a onclick="remove(2)">Remove</a></li>
    ...
</ul>

The user can remove items from the list by clicking the respective 'remove' links in the item. I want to reactively monitor this list for changes, so that when there are no items left it triggers a function. For example:

var num_list_items = $("#my_list li.relevant").length;
if( num_list_items == 0 ){
    do_something();
}

My app is being built in Meteor, so would ideally like to know if there is any native functionality that can do this. If not, any other suggestions are welcome.

Upvotes: 2

Views: 95

Answers (1)

MinusFour
MinusFour

Reputation: 14423

You can use a MutationObserver(link)

You'll instantiate one with something to do everytime the observed node mutates, if the mutation reports the desired condition you'll do something about it.

var observed = document.getElementById('my_list');
var whatIsObserved = { childList : true };
var mo = new MutationObserver(function(mutations){
    mutations.forEach(function(mutation){
       if(mutation.type === 'childList'){
          //DOM Tree mutated
          if(mutated.target.querySelectorAll('li.relevant').length === 0){
             //mutated target has no childs.
          }
       }
    });
});
mo.observe(observed, whatIsObserved);

Alternatively, have the remove function trigger your condition.

Upvotes: 2

Related Questions