Axiol
Axiol

Reputation: 5962

Add class to a specific parent element in CKEditor

I'm trying to build a small plugin to add a class to a specific tag in CKEditor. Here is what it should do: if the user is creating a list, wherever he is in that list, if he clicks the button, it adds a class to the ul parent.

I've managed to detect that tag. But, I can't find how to add a class and mainly, how to apply those changes after. Here is what I have right now:

editor = CKEDITOR.replace('editor');

editor.addCommand("testCommand", {
    exec: function(e) {
        parents = e.elementPath();
        parents = parents.elements;

        for (i = 0; i < parents.length; i++) {
            console.log('Check');

            if(parents[i].getName() ==  'ul') {
                console.log('List !');

                return true;
            }
        }
    }
});

editor.ui.addButton('testButton', {
    label: "Test button",
    command: 'testCommand',
    toolbar: 'insert',
    icon: 'Link'
});

Could you help?

Upvotes: 0

Views: 1397

Answers (1)

Wizard
Wizard

Reputation: 3151

Here's a JSFiddle.

CKEDITOR.addCss('ul.myclass { font-weight: bold; }'); // <-- CSS class declaration

const editor = CKEDITOR.replace('editor', {
    toolbar: [
        { name: 'paragraph', items: [ 'Source', 'BulletedList', 'testButton' ] }
    ],
    extraAllowedContent: 'ul(myclass)' // <-- needed for Advanced Content Filtering (ACF)
});

editor.addCommand("testCommand", {
    exec: function(e) {
        let parents = e.elementPath();
        parents = parents.elements;

        for (let i = 0; i < parents.length; i++) {
          console.log('Check');

          if (parents[i].getName() ==  'ul') {
            console.log('Liste !');
            parents[i].addClass('myclass'); // <-- adds the CSS class
            break;
          }
       }
    }
});

editor.ui.addButton('testButton', {
    label: "Test button",
    command: 'testCommand',
    toolbar: 'insert',
    icon: 'Link'
});

Upvotes: 2

Related Questions