5

I have a content editable div with some html elements in it. For example, let's say I have:

<div contenteditable="true" id="myTextArea">
   Some content, <div id="div1">content in div</div>, 
   and more <span id="span1">content</span></div>

When the user edits text in myTextArea and deletes some html element (either by pasting new content, or just backspacing text) I want each html element to fire an event and tell me that it was deleted. Any ideas on how I could do this?

Lukasz
  • 153
  • 1
  • 7
  • See this answer on a related question: http://stackoverflow.com/a/5614764/1615483 – Paul S. Oct 24 '12 at 01:34
  • Here is the MDN page on [`MutationObserver`](https://developer.mozilla.org/en-US/docs/DOM/MutationObserver?redirectlocale=en-US&redirectslug=DOM%2FDOM_Mutation_Observers), you'd be interested in `removedNodes`. – Paul S. Oct 24 '12 at 01:42
  • well, the "input" event doesn't seem to give me the object that actually caused the event and DOMNodeRemoved seems to be buggy (or I don't understand how it works) because it only sometimes works (e.g. on spans, rarely on divs). Anyone has this working? I could always take the diff and see what changed after the input event but I feel like there is got to be a better way of doing this. – Lukasz Oct 25 '12 at 22:07

1 Answers1

3

You could use a MutationObserver to achieve this. To track any sort of node removed from your contenteditable element, observe the following example

<div id="myTextArea" contenteditable="true">
    <input value="input" />
    <span contenteditable="false">span</span>
</div>

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {

        //console.log($(mutation.removedNodes)); // <<-- includes text nodes as well

        $(mutation.removedNodes).each(function(value, index) {
            if(this.nodeType === 1) {
                console.log(this) // your removed html node
            }
        });
    });
});

var config = { attributes: true, childList: true, characterData: true };

observer.observe($('#myTextArea')[0], config);

JSFiddle Link

scniro
  • 16,844
  • 8
  • 62
  • 106