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();
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/