Search code examples
javascriptdommutation-observers

How can I use MutationObserver on multiple nodes?


The following code allows me to listen for class changes on a single node:

var target = $(".right-border")[0]

var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(“Change”)
  });
  });

  var config = { attributes: true, childList: true, characterData: true };

 observer.observe(target, config);

If I have a grid of divs, for example, and each div on the right border has a class of right-border, how can I listen for changes on each one? I know that I could create multiple variables:

var target2 = $(".right-border")[1]
var target3 = $(".right-border")[2]

But is there a more efficient way of selecting each node? Is it possible to use a for loop somewhere in the above code that targets each div with a class of right-border?


Solution

  • You can use jQuery's each method to iterate over all matching DOM nodes and observe its mutations. The code is almost what you already have - notice that target = this which is how each node is targeted.

    var config = { attributes: true, childList: true, characterData: true };
    
    $(".right-border").each(function () {
      var target = this;
      var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
          console.log("Change")
        });
      });
    
      observer.observe(target, config);
    });