How do I add a CSS class to a p tag in CKEditor? The standard center button only applies a in-line style to the HTML.
But how can I add a class 'text-center' to a paragraph or selection by clicking the following icon? I went ahead and created a custom button on CkEditor.

(function($) {
CKEDITOR.plugins.add( 'center', {
    icons: 'center',
    init: function( editor ) {
        editor.addCommand( 'center', genCommand());
        editor.ui.addButton( 'center', {
            label: 'Align text on center',
            command: 'center',
            toolbar: 'center'

        });
        if ( editor.contextMenu ) {
            editor.addMenuGroup( 'centerGroup' );
            editor.addMenuItem( 'centerItem', {
                label: 'Change link',
                icon: this.path + 'icons/center.png',
                command: 'center',
                group: 'centerGroup'
            });
            editor.contextMenu.addListener( function( element ) {
                if ( element.getAscendant( 'center', true ) ) {
                    return { abbrItem: CKEDITOR.TRISTATE_OFF };
                }
            });
        }
        CKEDITOR.dialog.add( 'centerDialog', this.path + 'dialogs/center.js' );
    }
});
function genCommand( name ) {
    return {
            exec: function( editor ) {
                editor.insertHtml('&lt;p class="text-center&gt;' + editor.getSelection().getNative() + '&lt;/p&gt;');
            },
    };
}
})(jQuery);


What it is doing is nothing. In the case there is a selection, it deletes the selection and markup.

What I need:


If there is a line saying "text", I need &lt;p class="text-center"&gt;text&lt;/p&gt;
In the case there is a selection, make 1 out of the selection
Using WYSIWYG/CKEditor in Drupal, you can add classes in the UI and they will show up in the Style drop down.

In the CSS tab of the WYSIWYG Profile you are editing:



You need to have the "Font style" plugin checked off in the config.



Now any element you add here can have it applied, so you would add:

Center P Tag=p.text-center

line to this config.

Then, add some text in the editor, and highlight the text (CKEditor should automatically wrap regular text with a p tag). You should then see the option in the drop down as "Center P Text". You will only see these options available when you've highlighted elements that are applicable. It will then apply the class to the highlighted element, the p tag.

I use this all the time to add classes to various elements just as you are trying to do.