Search code examples
javascriptdommutation

Get Removed Nodes from contenteditable div(Froala Editor)


I'm trying to use MutationObserver to get removedNodes from contenteditable element(Froala Editor in this case) but instead of getting class of removed element in this case .comment I'm getting weird classes like .fr-marker. So what I'm looking is to everytime element with class .comment is removed from editor to log that element .data-comment attribute. I know how to handle getting data attribute once I get that removedNode.

Here is the fiddle with full example: https://jsfiddle.net/chille1987/urwoLqsf/16/

HTML

<div id="elem">
    <p>Click and <b>edit</b>, please</p>
    <p>Another paragraph goes here</p>
    <p>Third paragraph with <span class="comment" data-comment="2345">comment inside</span></p>
</div>

<link href="https://cdn.jsdelivr.net/npm/froala-editor@3.2.6/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/froala-editor@3.2.6/js/froala_editor.pkgd.min.js"></script>

And this is my JS file

var editor = new FroalaEditor('#elem', {
    events: {
        'initialized': function () {
            let observer = new MutationObserver(mutationRecords => {
                mutationRecords.forEach(mutation => {
                    mutation.removedNodes.forEach(node => {
                        console.log(node.classList.value)
                    })
                }); // console.log(the changes)
             });

            // observe everything except attributes
            observer.observe(document.querySelector('.fr-view'), {
                childList: true, // observe direct children
                subtree: true // and lower descendants to
            });
        }
    }
});

Comment class highlighted in css

.comment {
    background: yellow;
}

And here is the console after removing last paragraph with comment in it.

enter image description here


Solution

  • Actually, your code should work. What you see is how the Froala editor handles editing content. Eventually, you will get the correct element all you need to do is to filter the removed nodes:

    mutation.removedNodes.forEach(node => {
      if(node.nodeName === 'SPAN' && node.className === "comment"){            
          console.log(node.textContent)
          const attribute = node.attributes.getNamedItem("data-comment")
          console.log(attribute.value)
      }
    });
    

    Fiddle