Search code examples
javascriptckeditor

How to wrap selected text in ckeditor


I wanted to wrap selected words in CKEditor in a <p> element.

From:

<p>This is a paragraph. And this is Selected text.</p>

To:

<p>This is a paragraph. And this is</p>
<p class="myclass">Selected text.</p>

I found some code:

( function() {
    CKEDITOR.plugins.add( 'qna', { 
        init: function( editor ) {
            editor.addCommand( 'insertQnA', { 
                exec : function( editor ) {    
                    if(CKEDITOR.env.ie) {
                        editor.getSelection().unlock(true); 
                            var selected_text = editor.getSelection().getNative().createRange().text; 
                    } else { 
                        var selected_text = editor.getSelection().getNative();
                    }
                    editor.insertHtml('[before]' + selected_text + '[after]'); 
                } 
            }); 
            editor.ui.addButton( 'qna', { 
                label: 'Insert QnA', 
                command: 'insertQnA', 
                icon: this.path + 'images/qna.png'
            }); 
        } 
    });
})();

I wanted to replace the [before] and [after] with <p class"myclass"> and </p> but it doesn't work.

I'm quite a newbie in JS/Jquery. I hope you can shed some light on it for me.

EDIT: From Spon's reply.

( function() {
  CKEDITOR.plugins.add( 'qna', { 
    init: function( editor ) {
      editor.addCommand( 'insertQnA', { 
        exec : function( editor ) {    
          editor.applyStyle(new CKEDITOR.style({
            Element : 'p', 
            Attributes : { class : 'Myclass' }, 
            Styles : { color : '#ff0000','font-family' : 'Courier'} 
          }));
        } 
      }); 
      editor.ui.addButton( 'qna', { 
        label: 'Insert QnA', 
        command: 'insertQnA', 
        icon: this.path + 'images/question.png'
      }); 
    } 
  });
})();

The above code wraps the selected text/words in a <span> element for some unknown reason.

Example:

From...

<p>This is a paragraph. And this is Selected text.</p>

To...

<p>This is a paragraph. And this is <span>Selected text.</span></p>

This is not what I want.


Solution

  • exec : function( editor ) {
      var selected_text = editor.getSelection().getSelectedText(); // Get Text
      var newElement = new CKEDITOR.dom.element("p");              // Make Paragraff
      newElement.setAttributes({style: 'myclass'})                 // Set Attributes
      newElement.setText(selected_text);                           // Set text to element
      editor.insertElement(newElement);                            // Add Element
    }
    

    This will fix it.. This is the Exec part as you can see.