Not the problem is that MutationObserver works for #someID , but how to make it work for .someClass ?
#someID
.someClass
I am currently 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); }
You had a few problems:
target[i]
var foo = target[i].getAttribute("someAttribute")
i
target.length
foo.style.backgroundColor
observer.observe(target, config);
Here is the working code after fixing the above errors and urgently including the loop code in the function to simplify the link to the target:
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 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>
Here is an example with minimal changes:
var foo = mutation.target.getAttribute("someAttribute")
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 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>