Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
MutationObserver no se activa cuando cambia el texto

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();
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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/

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!