How to wrap selected text in ckeditor

Duplicate see Stackoverflow: Ckeditor Selection wrapping

editor.applyStyle(new CKEDITOR.style({Element : 'p', Attributes : { class : 'Myclass' }, Styles : { color : '#ff0000','font-family' : 'Courier' } ));

This piece of code makes sure that if you have multiple block level selection, that you will keep the same structure. (If you make your p.myclass inline offcourse).

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

this example will be merged and output as:

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

But this example:

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

this example will be merged and output as:

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

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.