Soy bastante nuevo en la programación y estoy tratando de desarrollar una extensión de Chrome. El sitio web que estoy tratando de manipular tiene un elemento div y dentro de este div hay múltiples div s y el número de estos div s varía según la escala del primer div y el usuario puede arrastrar la escala. Mi problema es que necesito declarar cada una de estas variables y hacer que un observador de mutaciones las observe en busca de cambios. Entonces, un usuario podría tener 8 div en la ventana arrastrable y otro usuario podría tener 12 div allí, así que quiero tener 8 o 12 observadores de mutación respectivamente. A continuación se muestra mi código:
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); Como puede ver, he creado 2 observadores de mutaciones y están observando dos div s, pero esto es práctico solo cuando el usuario tiene 2 de los div s en su ventana arrastrable. Realmente aprecio tu ayuda.
Use un bucle para agregar el observador de mutación a todos los DIV.
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); });