Search code examples
javascriptjquerydommutation-observers

Substituting DOMSubtreeModified for MutationObserver issues


I am trying to check if new table row(s) <tr> were added to the table like this:

var myTab;e = $('#myTable tbody');
myTab.on("DOMSubtreeModified", function() {
  console.log('Row added');
}); 

But this prints out to console 100's of 'Row added' messages, if for example 10 rows are added to the table simultaneously, even if one of them I't still prints out 'Row added' 10 times. This got me thinking that it is listening to absolutely all changes within myTable which is not what I want. I just want it to execute one time even if 100 rows are added (Rows are added in bulk couple at a time).

I found another solution via: MutationObserver but Can't figure out how to set it up in order to achieve my task (once rows are added to myTable) execute change event one time.

Here is example markup for the table.

<table id="myTable">
    <thead>
    <tr>
     <th>
      <div>Date</div>
      <span>Time</span>
   </th>
    </tr>
    </thead>

    <tbody>
    <tr>
      <td>Content</td>
      <td>More content</td>
    </tr>

    <tr>
      <td>Content</td>
      <td>More content</td>
    </tr>

    <!-- etc.. -->
  </tbody>
</table>

This is a very simple version of it with things like classes, data attributes, id's and other elements omitted, but should do the trick.


Solution

  • var target = $("#myTable").get(0);
    
    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        // do stuff when
        // `childList`, `subtree` of `#myTable` modified
        alert(mutation.type);        
      });    
    });
    
    // configuration of the observer:
    var config = { childList: true, subtree:true };
    
    // pass in the target node, as well as the observer options
    observer.observe(target, config);
    
    $("#myTable tbody").append("<tr><td>abc</td></tr><tr><td>def</td></tr>")
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <table id="myTable">
        <thead>
        <tr>
         <th>
          <div>Date</div>
          <span>Time</span>
       </th>
        </tr>
        </thead>
    
        <tbody>
        <tr>
          <td>Content</td>
          <td>More content</td>
        </tr>
    
        <tr>
          <td>Content</td>
          <td>More content</td>
        </tr>
    
        <!-- etc.. -->
      </tbody>
    </table>