When we try to add nested nodes in DOM using appendChild or innerHTML, the nested nodes do not come in the addedNodes of a mutation.
Initial HTML setUp:
<html>
<body>
<div id="container">
</div>
</body>
</html>
Here is my Mutation Observer code:
var observer = new MutationObserver(function(mutations) {
for (var i = 0; i < mutations.length; i++) {
var mutation = mutations[i];
switch(mutation.type) {
case 'childList':
console.log(mutation.addedNodes);
break;
default:
}
}
});
observer.observe(document, {
childList: true,
subtree: true,
attributes: true,
characterData: true
});
If I now do appendChild with a nested img node in a div,
var img = document.createElement('img');
img.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
var div = document.createElement('div');
div.appendChild(img);
var container = document.getElementById("container");
container.appendChild(div);
The Mutation Observer only logs the div which is appended to the container, but does not log the img as an addedNode in mutation.
Here is a working JSFiddle: https://jsfiddle.net/aedhefhn/
Is there a workaround for this?
tag for some reason. I just found out when I couldn't get a nodeList.forEach to see the change even when polling the DOM as a whole detected one. I have to remove that pesky
tag and it should be fine. It was working ok before. I'm trying to use multiple summernotes and changed from
tag isn't the solution. Writing accurate looping code to parse through the child nodes IS the solution!
– Dennis H Feb 19 '23 at 04:05