14-day Cloud trial
Start today. For free.

One editor. 50+ features. Zero constraints. After your trial, retain the advanced features.

Try Professional Plan for FREE
PricingContact Us
Log InGet Started

How to get content and set content in TinyMCE

June 2nd, 2023

4 min read

All kinds of content including text, video, and images being collected and set in an editor

Written by

Ben Long

Category

Developer Insights

Some of the most common questions we are asked by developers, when they’re integrating TinyMCE with their apps for the first time, are about how to get content and set content in the editor.

So here’s a brief guide on the relevant TinyMCE API methods, as well as some of the other commonly asked questions, like:

  • How to set content on initialization 
  • How to get the content without any HTML tags
  • Why isn’t the getContent working?

This article also explains how to fix errors and troubleshoot if you’re finding get content and set content aren’t working.

 

TABLE OF CONTENTS

The TinyMCE getContent and setContent methods

How to use the setContent methods

How to setContent with multiple editors

TinyMCE setContent not working

How to set TinyMCE content on initialization

How to get content in TinyMCE without any HTML tags

What’s essential for getting and setting content

 

The TinyMCE getContent and setContent methods

Once a user has entered content in the editor, you’ll probably want to save the content to a database somewhere, in which case you’ll need to get the content first. You can do this using the getContent() API method.

Let’s say you have initialized the editor on a textarea with id=”myTextarea”.

For instance:

<script src="https://cdn.tiny.cloud/1/your-tinymce-apikey/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
 <script>
        tinymce.init({
            // Select the element(s) to add TinyMCE to using any valid CSS selector
            selector: "#myTextarea",
            plugins: "preview powerpaste casechange searchreplace autolink autosave save directionality advcode visualblocks visualchars fullscreen image link media mediaembed template codesample advtable table charmap pagebreak nonbreaking anchor advlist lists checklist wordcount tinymcespellchecker a11ychecker help formatpainter permanentpen pageembed linkchecker emoticons export",
            height: '700px',
            toolbar_sticky: true,
            icons: 'thin',
            autosave_restore_when_empty: true,
            content_style: `
                body {
                    background: #fff;
                }

                @media (min-width: 840px) {
                    html {
                        background: #eceef4;
                        min-height: 100%;
                        padding: 0 .5rem
                    }

                    body {
                        background-color: #fff;
                        box-shadow: 0 0 4px rgba(0, 0, 0, .15);
                        box-sizing: border-box;
                        margin: 1rem auto 0;
                        max-width: 820px;
                        min-height: calc(100vh - 1rem);
                        padding:4rem 6rem 6rem 6rem
                    }
                }
            `,
        });
    </script>
    <style>
        body {
            margin: 4rem auto;
            padding: 0 2rem;
            background-color: #f9f9fb;
        }
        main {
            width: 100%;
        }
    </style>
</head>
<body>
<main>
    <textarea id="myTextarea">
        <h1 style="text-align: center;">Getting and Setting Content</h1>
        <p style="text-align: center;">Use the only WYSIWYG editor that’s trusted by <a href="<a href="https://tiny.cloud">https://tiny.cloud</a>" target="_blank" rel="noopener">1.5M developers</a>.</p>
    </textarea>
</main>
</body>
</html>

What you can do is, access the content in the editor with the command tinymce.activeEditor.getContent("myTextarea"); specifying the editor id. You can run this command to get the editor content. Here’s how it goes in a variable (More on variables later in this article):

var myContent = tinymce.get("myTextarea").getContent();

This will return the content in the editor marked up as HTML.

Or, instead of accessing the editor by id, you can access the active editor. This is good if you have just one editor in your app:

var myContent = tinymce.activeEditor.getContent();

Here’s an example:

Getting content with TinyMCE Editor API command

How to use the setContent methods

When you’re using TinyMCE in your apps, and a user requirement is to edit content previously stored somewhere else (like in a CMS, which Tiny works well with), what you need is a way to populate the editor with that content.

You can do this using the setContent() API method.

There’s a few different ways you can do this.

If you’ve got one active editor on the page, run this command:

tinymce.activeEditor.setContent("<p>Hello world!</p>");

If you have more than one editor on the page, specify the id, and run the get command:

tinymce.get("myTextarea").setContent("<p>Hello world!</p>");

Put the get command in a function:

function Setcontent() {
     var ContentSet = tinymce.get('editorOne').setContent(‘<p>Hello World!’</p>);
    }

Then run the setContent() method in the function with a DOM related event:

var buttonSet = document.getElementById("buttonOne");
buttonSet.addEventListener("click", Setcontent, false);

Here’s the setContent() method working as a command:

TinyMCE set content command running in editor

And here’s how the setContent() method works as a function.

This is the script:

</html>
   <body>
      <form method="post" action="dump.php">
                <textarea class="myTextarea" id="editorOne">
                  <p>That Kermit Gif</p>
                </textarea>
      </form>
      <button id='buttonOne' class="button_style" name="New Content">Press to set new content</button>
    </body>
    <script>
    const contentOne = '<h1 style="text-align: center;">Getting and Setting Content</h1> <p style="text-align: center;">Use the only WYSIWYG editor that’s trusted by <a href="https://tiny.cloud" target="_blank" rel="noopener">1.5M developers</a>.</p>'
    function Setcontent() {
     var ContentSet = //The function works with tinymce.activeEditor.setContent(contentOne); too.
    tinymce.get('editorOne').setContent(contentOne);
    }
    var buttonSet = document.getElementById('buttonOne');
    buttonSet.addEventListener('click', Setcontent, false);
    </script>
</html>

And here’s the script in action:

Set Content working as a function

Note: The function works with the tinymce.activeEditor.setContent(contentOne); command too.

Get the content and save the content

Check out our previous article where we save to and load from our rich text editor using JavaScript and localStorage. After the TinyMCE editor is added to the initial example, the save and load functions are updated to access the editor content using these methods.

How to setContent with multiple editors

If you have multiple editors, set the specific id of the editor you want to change in your command or your function. For instance, in this index.html file, here’s how the get and set content works with another textarea added to the previous setContent example:

<form method="post" action="dump.php">
                 
  <textarea class="myTextarea" id="editorOne">
                       <p>That Kermit Gif</p>
                  
  </textarea>
                
  <textarea class="myTextarea" id="editorTwo">
                       <p>That Kermit Gif</p>
                  
  </textarea>
   
</form>;

Running the setContent() function on specifically editorOne with the tinymce.get('editorOne').setContent(contentOne); method, you can change just editorOne.

Here’s the change in action:

TinyMCE set content with multiple editors

TinyMCE setContent not working

You may run into an error where setContent is not working. Like the (annoying) “Cannot read property 'setContent' of null” error.

To fix this one, and other similar errors like “undefined”, check on the order of events in your JavaScript.

 

Make sure that your API call with the getContent method runs after your tinymce.init script.

Setting the setContent() method to run on initialization could also be the solution to the problem.

How to set TinyMCE content on initialization

Often you want the editor populated with content as soon as it’s initialized. In this case, you can use the setup option in the editor config.

For example:

<script>
  tinymce.init({
    selector: '#myTextarea',
    setup: function (editor) {
      editor.on('init', function (e) {
        editor.setContent('<p>Hello world!</p>');
      });
    }
  });
</script>

Again, check out the JavaScript localStorage example, where towards the end, the load button is exchanged for the ability to add the content on initialization.

How to get content in TinyMCE without any HTML tags

Depending on your use case, sometimes you might want to get the TinyMCE content without the HTML markup. In this case, when calling getContent, you can pass in a parameter to indicate that, instead of returning HTML, you want the result in plaintext.

For example:

var myContent = tinymce.get("myTextarea").getContent({ format: "text" });

What’s essential for getting and setting content

Always double check the order of events loading and running on the page.

Confirm whether the TinyMCE editor has been initialized before your setContent script runs. Remember that you can place the setContent method so that it runs on the tinymce.init script as the page loads.

While we’re talking about getting and setting TinyMCE content, you might also be interested to know…Tiny provides clean copy/paste of content from Word, Excel, and other popular content tools. Check out the PowerPaste plugin.

There’s an Autosave plugin that comes free with TinyMCE to save your users the frustration of losing their work based on connectivity or other issues outside their control.

Not already using TinyMCE on the Cloud? Get a free API Key and try it out. It’s super easy to set up. You also get a 14-day FREE trial of the full suite of premium plugins.

TinyMCEAPIIntegrationJavascript
byBen Long

Computer scientist, storyteller, teacher, and an advocate of TinyMCE. Reminisces about programming on the MicroBee. Writes picture books for kids. Also the wearer of rad shoes. “Science isn’t finished until you share the story.”

Related Articles

  • Developer InsightsMay 13th, 2020

    How to add rich text editor in Django

Join 100,000+ developers who get regular tips & updates from the Tiny team.