MutationObserver for class (not for id)

john c. j. picture john c. j. · Jan 30, 2016 · Viewed 12.8k times · Source

It's not the problem to make MutationObserver work for #someID, but what's the way to make it work for .someClass?

Currently I'm using the following:

// this example doensn't work,
// as well as many another attempts

var target = document.querySelectorAll(".someClass");
for (var i = 0; i < target.length; i++) {

    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            var foo = target[i].getAttribute("someAttribute")

            if (foo == "someValue")
                foo.style.backgroundColor = "red";
        });
    });

    // configuration of the observer
    var config = { attributes: true };

    // pass in the target node, as well as the observer options
    observer.observe(target, config);
}

Answer

Shomz picture Shomz · Jan 30, 2016

You had a few issues:

  • iterator: target[i] is not what you expect once the code is executed (var foo = target[i].getAttribute("someAttribute")), since the iteration is finished when this line is ran, i has a value of target.length, so target[i] does not exist
  • attributes don't have styles (foo.style.backgroundColor), you need to refer the target element
  • you're passing the whole collection to the observer (observer.observe(target, config);) you need only one target element

Here's the working code after fixing the errors listed above and externalizing the loop code into a function for easier target referencing:

var target = document.querySelectorAll(".c");
for (var i = 0; i < target.length; i++) {
  create(target[i]);
}

function create(t) {
  // create an observer instance
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      var foo = t.getAttribute("aaa")

      if (foo == "vvv")
        t.style.backgroundColor = "red";
    });
  });
  // configuration of the observer
  var config = {
    attributes: true
  };

  // pass in the target node, as well as the observer options
  observer.observe(t, config);
}

// let's change an attribute in a second
setTimeout(function(){
  target[2].setAttribute('aaa', 'vvv');
}, 1000);
.c {
  width: 50px;
  height: 50px;
  display: inline-block;
  border: 1px solid black
}
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>
<div class="c"></div>


UPDATE

Here's an example with minimal edits:

  • var foo = target[i].getAttribute("someAttribute") changed to var foo = mutation.target.getAttribute("someAttribute") instead of a passed-in target element

var target = document.querySelectorAll(".someClass");
for (var i = 0; i < target.length; i++) {

    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            var foo = mutation.target.getAttribute("someAttribute")

            if (foo == "someValue")
                mutation.target.style.backgroundColor = "red";
        });
    });

    // configuration of the observer
    var config = { attributes: true };

    // pass in the target node, as well as the observer options
    observer.observe(target[i], config);
}

// let's change an attribute in a second
setTimeout(function(){
  target[2].setAttribute('someAttribute', 'someValue');
}, 1000);
.someClass {
  width: 50px;
  height: 50px;
  display: inline-block;
  border: 1px solid black
}
<div class="someClass"></div>
<div class="someClass"></div>
<div class="someClass"></div>
<div class="someClass"></div>