Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tinyMCE 4: add Class to selected Element

I created a tinymce menu item and what I want it to do is add a class to the selected text element. I cannot seem to figure out how to do this. Any suggestions? Adding my menu item looks like this:

tinymce.PluginManager.add('button', function(editor, url) {
    editor.addMenuItem('button', {
        icon: '',
        text: 'Button',
        onclick: function() {

            tinyMCE.activeEditor.dom.addClass(tinyMCE.activeEditor.selection, 'test'); //not working
        },
        context: 'insert',
        prependToContext: true
    });
});

I'd be very thankful for any helpful hint.

like image 991
Chi Avatar asked Nov 13 '15 09:11

Chi


2 Answers

I found a solution that may not be perfect (for example, if you select part of a text then this doesn't work as I hoped), but for now it does what I want:

tinyMCE.activeEditor.dom.addClass(tinyMCE.activeEditor.selection.getNode(), 'test');

if I do this on a link, for example, the scripts add the classname "test" to my tag.

like image 84
Chi Avatar answered Oct 14 '22 11:10

Chi


In order to be able to add a class to the editor you need a dom element in the editor to add the class to. Textnodes may not hold a class. So i propose you insert a span element with the class you want to add wrapped around the actual selection. Be aware that this won't work if the selection leaps over paragraph boundaries (in this case you will need a bit more complicated code). Try this:

onclick: function() {
    var ed = tinyMCE.activeEditor;
    var content = ed.selection.getContent({'format':'html'});
    var new_selection_content = '<span class="test">' + content + '</span>';
    ed.execCommand('insertHTML', false, new_selection_content);
},
like image 25
Thariama Avatar answered Oct 14 '22 11:10

Thariama