Skip to content Skip to sidebar Skip to footer

Mutationobserver Records Wrong Dom Element (editable Div)

Consider the following: I have a contenteditable div:

Lorem ipsum...

var mutationObserver = newMutationObserver(function(mutations) {
	mutations.forEach(function(mutation) {
		manipulateAddedContent(mutation);
	});
});

mutationObserver.observe(jQuery("#contentEditableDiv")[0], 
  { attributes: true, childList: true, characterData: true });

functionmanipulateAddedContent(mutation){
	jqMutation = jQuery(mutation);
	if(jqMutation.prop("addedNodes").length > 0){
		for (i = 0; i < jqMutation.prop("addedNodes").length; i++) {
		    if(typeofjQuery(mutation.addedNodes[i]).next()[0] !== "undefined"){
			    console.log(jQuery(mutation.addedNodes[i]).next()[0]);
		    }
		}
	}
}
#contentEditableDiv {
		border: 1px solid black;
		min-height: 200px;
		width: 200px;
	}

	#contentEditableDivp{
		border: 1px solid red;
		margin-left: 5px;
		margin-right: 5px;
	}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><divid="contentEditableDiv"contenteditable="true" ><pid="content0">Lorem ipsum...</p><pid="content1">Lorem ipsum...</p></div>

But I will not accept my answer cause I still do not know WHY the mutationObserver returns the wrong element.

Solution 2:

This has nothing to do with MutationObserver, it's not returning the wrong element. When you press enter inside any element within a contenteditable container it gets duplicated, which is why the element reported by MutationObserver has the same id. If you try to locate the element through DevTools, it will show you the most recently added one - because it has the same id.

#uniqueOrIsIt {
 border: 1px solid gold;
}
.paragraph {
 border: 1px solid blue;
}
<divcontenteditable="true"><pid="uniqueOrIsIt">text</p><pclass="paragraph">text</p><pstyle="border: 1px solid green;color:green">text</p></div>

All three of the p elements will get duplicated with the exact same attributes.

The solution depends on what you're trying to accomplish - do you want each inserted p element to have a new unique id? In that case you can, for each mutation, check if any of the addedNodes are p elements and if they are, assign them a unique id. Keep a simple let counter = 1 and set the ids as addedNode.setAttribute('id', ('content' + counter++))

Post a Comment for "Mutationobserver Records Wrong Dom Element (editable Div)"