Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

100
Visualizações
MutationObserver doesn't trigger when text changes

I have a simple tag on my html page

<div id="myid">My text</div>

Im new to JavaScript. I need that MutationObserver detect when text changes in "My text" here is my JavaScript code


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();
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you want to detect changes of a text field you can simply use onChange event, for example:

<input type="text" id="myid"/>

<script>
    let sel = document.getElementById('myid');
    sel.addEventListener ("change", function (data) {
       console.log(data.currentTarget.value);
    });
</script>
    

MutationObserver is good to use when you want to subscribe on DOM changes - like attribute changes etc. That's why youк code doesn`t work, because you don't have any changes related to DOM structure. See example with additionally adding new attribute:

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";

If you want to play with it, please see: https://jsfiddle.net/a0vdxt5n/40/

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda