Dynamically Remove a Summernote Instance with jQuery

I’ve been developing a page that gets loaded with multiple instances of the WYSIWYG text editor Summernote. An issue arose when the user attempted to remove a node which contained a Summernote instance. The jQuery .remove() method was attached to a button, which would remove the node that contained the Summernote instance. When the form was submitted, I would get an error:

Uncaught TypeError: Cannot read property 'val' of undefined  

I couldn’t track down the root of the error, but Summernote was looking for a val() that it couldn’t find. The correct node and child elements had been removed from the DOM, but Summernote seemed to think it was still there. I tried the .destroy() method of Summernote before the jQuery .remove() to no avail. In the end, I ended up using the jQuery method .detach() instead of .remove() which “keeps all jQuery data associated with the removed elements.” On submission, Summernote acts correctly and, since the DOM node had been removed, my data persisted correctly in the back-end.

Photo by Cameron Kirby at Unsplash