Ckeditor5: How to add custom class when using writer.insertText

Created on 11 Dec 2020  Â·  2Comments  Â·  Source: ckeditor/ckeditor5

Provide a description of the task

I using insertText() to create new paragraph, how can i add custom class for new element?

_What steps should be taken to fulfill the task?_
Here is my code:
`js
const docFrag = editor.model.change(writer => {

            const p1 = writer.createElement('paragraph', {class: 'flashback'});

            const docFrag = writer.createDocumentFragment();

            writer.append(p1, docFrag);

            writer.insertText('※   ※   ※', p1);

            return docFrag;
        });

`

  • Browser: Chrome
  • OS: Window
  • CKEditor version: 5
question

All 2 comments

Hi, thanks for the report. Did you allow class attribute on the paragraph element in the schema and provide proper conversion for this attribute? The simplified implementation could look like this:

import Plugin from '@ckeditor/ckeditor5-core/src/plugin';

export default class AllowClassAttribute extends Plugin {
    init() {
        const editor = this.editor;

        editor.model.schema.extend( 'paragraph', { allowAttributes: [ 'class' ] } );

        editor.conversion.attributeToAttribute( { model: 'class', view: 'class' } );
    }
}

Hi, thanks for the report. Did you allow class attribute on the paragraph element in the schema and provide proper conversion for this attribute? The simplified implementation could look like this:

import Plugin from '@ckeditor/ckeditor5-core/src/plugin';

export default class AllowClassAttribute extends Plugin {
    init() {
        const editor = this.editor;

        editor.model.schema.extend( 'paragraph', { allowAttributes: [ 'class' ] } );

        editor.conversion.attributeToAttribute( { model: 'class', view: 'class' } );
    }
}

Thanks @Mgsy, it worked.

Was this page helpful?
0 / 5 - 0 ratings