MutationObserver

Änderungen am DOM-Baum überwachen und darauf reagieren

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<!DOCTYPE html>
<div id="list">
  <a id="hello">Item 1</a>
  <a>Item 2</a>
  <a>jhghj</a>
</div>

CSS

a {
  display: block
}

JavaScript

var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
  var list = document.querySelector('#list');
  var isReordering = false;
  var weight = 'weight';

  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {

      if (isReordering) return;
      isReordering = true;

      console.log(mutation);
      if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {

				// Neue DOM-Knoten wurden hinzugefügt:
        var children = jQuery(list).children().toArray();
        var list$ = jQuery(list);
        console.log(children);
        var orderedChildren = _(children).sortBy(function(node) {
          return jQuery(node).data(weight) || 0
        });
        console.log(orderedChildren);
        for (var i in orderedChildren) {
          jQuery(orderedChildren).appendTo(list$);
        }
        // ENDE: Neue DOM-Knoten wurden hinzugefügt
        
      }
    });
    isReordering = false;
  });

  observer.observe(list, {
    attributes: false,
    childList: true,
    characterData: false
  });

  jQuery('#list').append('<a id="n1" data-weight="-1">-1</a>');
  jQuery('#list').append('<a id="n2" data-weight="-10">-10</a>');