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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.