Search code examples
javascripttinymce

TinyMCE insertHTML modifies some HTML tags


I have some content in tinymce 6 editor. I moved the cursor and placed it inside the content and executed

tinymce.activeEditor.insertContent(`<span class='dummy'>
                        <div><span style="font-style:italic;font-weight:bold;text-decoration:underline;">This Text is BOLD</span></div>
                        <div><span style="font-style:italic;">This text is Italic</span></div>
                        <div><span style="text-decoration:underline;">This Text is&#160; Underlined</span></div>
                      </span>`, {format: 'html'});

When I execute this the div elements are getting removed.

I can see the content inside the BeforeSetContent event. But on the SetContent event the content is getting modified and the div are removed. Is there any way to prevent this behaviour ?

I tried adding

valid_children: '+div[span], +span[div]' 

in the editor config.

I am expecting the html content to be added into the tinymce 6 editor without modifying the tags


Solution

  • The default behavior is to remove certain elements, such as <div>, when they are inserted using the insertContent method.
    But you can override this behavior by customizing the editor's schema and adding a rule to allow the <div> element:

    tinymce.init({
      selector: '#your-selector',
      // other configurations...
      setup: function (editor) {
        editor.on('BeforeSetContent', function (e) {
          // Allow the <div> element in the content
          e.content = e.content.replace(/<div>/g, '<div data-mce-bogus="1">');
        });
      },
      valid_elements: 'div[*]' // Allow all attributes on <div> elements
    });