How to fire an event when an HTML element is deleted in the content

I have editable content div with some html elements in it. For example, suppose 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 the text in myTextArea and removes some html element (either by inserting new content, or just by the inverse text), I want each html element to fire an event and tell me that it was deleted. Any ideas on how I can do this?

+4
source share
1 answer

You can use MutationObserver . To track any kind of node removed from your contenteditable element, take a look at 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

+2
source

Source: https://habr.com/ru/post/1441700/


All Articles