2

I want to add a class to a table inserted in CKEditor.

I have tried to add a custom style using the styles dropdown and add this line, table.my-custom-class|Table, but when clicking on the table the styles dropdown is not activated and I'm not able to add the class.

Is this possible to do with the styles dropdown?

I do use the ckeditor_tabletoolstoolbar module, so alternativaly I can add a custom button to the toolbar, but I don't know how to do that either?

I have seen this thread, but it's for CKEditor 3, I'm using CKEditor 4.

I want to be able to toggle the class, so it's removed when clicking the button again.

How can I solve this problem?

1 Answer 1

2

I solved the problem by creating a custom CKEditor plugin.

This is the JS code, in case anyone find it helpful:

CKEDITOR.plugins.add('tableclass', {
  beforeInit: function (editor) {
    editor.ui.addButton('addtableclass', {
      label: 'Add table class.',
      command: 'addTableClass',
      icon: '/modules/custom/mymodule/icons/add.png'
    });
  },
  init: function (editor) {
    editor.addCommand('addTableClass', {
      canUndo: true,
      exec: function (editor, data) {
        const className = 'custom-class';
        var selection = editor.getSelection();
        var selectedElement = selection.getStartElement().$;

        if (selectedElement.localName === 'table') {
          selectedElement.classList.toggle(className);
        }
        else {
          selectedElement = selectedElement.parentNode;
          while (selectedElement && selectedElement.localName !== 'table') {
            selectedElement = selectedElement.parentNode;
          }
          if (selectedElement.localName === 'table') {
            selectedElement.classList.toggle(className);
          }
        }
      }
    });
  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.