Consider the following:
I have a contenteditable
div:
<div id="contentEditableDiv" contenteditable="true">
<p id="content0e">Lorem ipsum...</p>
<p id="content1e">Lorem ipsum...</p>
</div>
I add a MutationObserver to observe DOM changes in this div in JavaScript:
var mutationObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
manipulateAddedContent(mutation);
});
});
mutationObserver.observe(jQuery("#contentEditableDiv")[0],
{ attributes: true, childList: true, characterData: true });
After solving this issue I want to manipulateAddedContent
. Yet the function is declared like this:
function manipulateAddedContent(mutation){
jqMutation = jQuery(mutation);
if(jqMutation.prop("addedNodes").length > 0){
for (i = 0; i < jqMutation.prop("addedNodes").length; i++) {
console.log(mutation.addedNodes[i]);
}
}
}
In the contenteditable
div it is possible to add a new p
DOM Element by pressing enter inside an existing p
element, so the HTML looks like:
Inspector:
<div id="contentEditableDiv" contenteditable="true" style="...">
<p id="content0e">Lorem ipsum...</p>
<p id="content1e">Lorem ipsum...</p>
<p></p>
</div>
But the MutationObserver records the already existing p
element with id="content1e"
.
Well, with the anticipation that the MutationObserver won´t do it right, I am also happy if you could give me an alternative solution.
Below is a Stack Snippet. If you click with the cursor inside one of the existing p
elements and press enter a new p
element gets created. The MutationObserver records the already existing p
element, but not the newly created one.
Stack Snippet:
var mutationObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
manipulateAddedContent(mutation);
});
});
mutationObserver.observe(jQuery("#contentEditableDiv")[0],
{ attributes: true, childList: true, characterData: true });
function manipulateAddedContent(mutation){
jqMutation = jQuery(mutation);
if(jqMutation.prop("addedNodes").length > 0){
for (i = 0; i < jqMutation.prop("addedNodes").length; i++) {
console.log(mutation.addedNodes[i]);
}
}
}
#contentEditableDiv {
border: 1px solid black;
min-height: 200px;
width: 200px;
}
#contentEditableDiv p{
border: 1px solid red;
margin-left: 5px;
margin-right: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="contentEditableDiv" contenteditable="true" >
<p id="content0">Lorem ipsum...</p>
<p id="content1">Lorem ipsum...</p>
</div>
So why does the MutationObserver records the wrong Element?
How can I fix it? => How get the newly added p
element (without id)?