Removing dynamically generated TinyMCE editor instances from the DOM

December 3, 2013, 8:23 pm
Author: James Griffiths

Here are the steps we went through to finally reach a solution.

1st attempt

Try to programmatically clear each editor instance, via the following script block:

for (var i=0; i<=length; i++) {
tinyMCE.execCommand('mceRemoveControl',false, tinymce.editors[i].id);
};

The problem with this approach? The editors were being visually removed from the browser window but references to the number of previously existing editor instances were not only kept but were also being incremented on the next dynamically added tinyMCE instance. This was resulting in a number of editor instances being recorded in the DOM when they weren't actually there on the page.This is easy to check by running the following code after each dynamically added TinyMCE instance:

console.log('Number of editors: ' + tinyMCE.editors.length);

2nd attempt

Implement a similar approach using a slightly different TinyMCE method:

for (var i=0; i<=length; i++) {
tinyMCE.editors[i].remove();
};

Hmm. Same result as before - editor instances were not being cleared from the DOM even if they were visually being removed from the browser window.

Crossing the hurdle

After much head scratching (and various expletive laden outbursts) we finally found the solution and boy, did it floor us. It turned out that the most effective way to clear ALL TinyMCE editor instances was also the simplest. Just re-initialise the editors array with the following declaration:

tinyMCE.editors.length = 0;

And how do we know this actually works? Easy, just place the following code snippet before and after the above array re-initialisation declaration:

console.log('Number of editors: ' + tinyMCE.editors.length);

When you run your script in the browser DOM inspector you'll see the editor instances are not being continually incremented anymore but are completely cleared from the DOM before being added again.

Neat, huh?

Categories

« Return to Posts

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.