Im pretty new to programming and im trying to develop a chrome extension. The website that im trying to manipulate has a div element and within this div are multiple divs and the number of these divs varies depending on the scale of the first div and the scale is draggable by the user. My problem is that, I need to declare each of these variables and have a mutation observer observe them for changes. So a user might have 8 div in the draggable window and another user might have 12 div in there so I want to have 8 or 12 mutation observers respectively. Below is my code:
span1 = document.getElementsByClassName("text right")[0];
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
var spantext = span1.textContent;
var spandiv = span1.parentNode;
if (mutation.addedNodes) {
if (spantext > avg) {
spandiv.style.backgroundColor = "#E8E8E8"
spandiv.style.color = "black";
spandiv.style.opacity = "0.7";
}
if (spantext < avg) {
spandiv.style.backgroundColor = "black";
spandiv.style.color = "white";
spandiv.style.opacity = "1";
}
}
})
});
const options = {
childList: true,
subtree: true,
attributes: true,
characterData: true
};
observer.observe(span1, options);
span2 = document.getElementsByClassName("text right")[1];
const observer2 = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
var spantext = span2.textContent;
var spandiv = span2.parentNode;
if (mutation.addedNodes) {
if (spantext > avg) {
spandiv.style.backgroundColor = "#E8E8E8"
spandiv.style.color = "black";
spandiv.style.opacity = "0.7";
}
if (spantext < avg) {
spandiv.style.backgroundColor = "black";
spandiv.style.color = "white";
spandiv.style.opacity = "1";
}
}
})
});
observer2.observe(span2, options);
As you can see I have made 2 mutation observers and they are observing two divs but this is practical only when the user has 2 of the divs in their draggable window.
I really appreciate your help.
Use a loop to add the mutation observer to all the DIVs.
document.querySelector(".text.right").forEach(span => {
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var spantext = span.textContent;
var spandiv = span.parentNode;
if (mutation.addedNodes) {
if (spantext > avg) {
spandiv.style.backgroundColor = "#E8E8E8"
spandiv.style.color = "black";
spandiv.style.opacity = "0.7";
}
if (spantext < avg) {
spandiv.style.backgroundColor = "black";
spandiv.style.color = "white";
spandiv.style.opacity = "1";
}
}
})
});
const options = {
childList: true,
subtree: true,
attributes: true,
characterData: true
};
observer.observe(span, options);
});