Tengo una etiqueta simple en mi página html
<div id="myid">My text</div>Soy nuevo en JavaScript. Necesito que MutationObserver detecte cuando cambia el texto en "Mi texto" aquí está mi código JavaScript
var target = document.querySelector("#myid"); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log(mutation.type); }); }); var config = { childList: true, attributes: true, characterData: true, subtree: true, attributeFilter: ["myid"], attributeOldValue: true, characterDataOldValue: true } observer.observe(target, config); observer.disconnect();Si desea detectar cambios en un campo de texto, simplemente puede usar el evento onChange , por ejemplo:
<input type="text" id="myid"/> <script> let sel = document.getElementById('myid'); sel.addEventListener ("change", function (data) { console.log(data.currentTarget.value); }); </script> MutationObserver es bueno para usar cuando desea suscribirse a cambios DOM, como cambios de atributos, etc. Es por eso que su código no funciona, porque no tiene ningún cambio relacionado con la estructura DOM. Vea el ejemplo con la adición adicional de un nuevo atributo:
const targetNode = document.getElementById('myid'); // Options for the observer (which mutations to observe) const config = { attributes: true, childList: true, subtree: true }; // Callback function to execute when mutations are observed const callback = function(mutationsList, observer) { // Use traditional 'for loops' for IE 11 for(const mutation of mutationsList) { if (mutation.type === 'childList') { console.log('A child node has been added or removed.'); } else if (mutation.type === 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.'); } } }; // Create an observer instance linked to the callback function const observer = new MutationObserver(callback); // Start observing the target node for configured mutations observer.observe(targetNode, config); //MODIFY THE ATTIBUTE TO SEE THE CHANGE targetNode.style["color"] = "red";Si quieres jugar con él, consulta: https://jsfiddle.net/a0vdxt5n/40/