Inserting content into TinyMCE

When developing a plugin for TinyMCE, you often need to insert content into the document. In most cases, this content is at the current cursor position, or selection. But what if you want to enter the content at the beginning or end of the document, irrelevant of the current cursor position?

In the following examples I assume you have a reference to the editor (ed). This may be as simple as getting the activeEditor.

var ed = tinyMCE.activeEditor;

Unlike the insertion of content at the current cursor position, which simply uses the selection object

ed.selection.setContent("some content");

insertion of content into other parts of the document require the dom object.

Let’s start with inserting into the end of the document. Fortunately TinyMCE provides a dom api call to add an element. So, if we provide a reference to the document using ed.getBody(), we can insert a new element. For example

ed.dom.add(ed.getBody(), 'p', {}, “some content”);

inserts a new paragraph at the end of the document.

Inserting content at the beginning of the document however is a bit more tricky. In this case, there isn’t a helper, so we need to first create the new element, and then insert it before the first child of the document. Again, there is a dom helper to assist in the creation

var el = ed.dom.create('p', {id : 'test', 'class' : 'myclass'}, 'some content');

We then use the insertBefore() method providing a reference to the firstChild of the document.

ed.getBody().insertBefore(el, ed.getBody().firstChild);

Leave a Reply

Your email address will not be published.