CKEditor is a powerful and widely used web-based WYSIWYG editor that provides users with a user-friendly interface for content creation. While CKEditor offers a range of built-in features and functionality, there may be instances where you need to insert custom HTML elements into your content. In this blog, we will explore how to insert custom HTML elements in CKEditor and enhance the editor’s capabilities to suit your specific needs.
Here’s an example that demonstrates the use of CKEditor’s insertElement()
method to achieve a similar result:
const docFrag = editor.model.change( writer => {
const p1 = writer.createElement( 'paragraph' );
const p2 = writer.createElement( 'paragraph' );
const blockQuote = writer.createElement( 'blockQuote' );
const docFrag = writer.createDocumentFragment();
writer.append( p1, docFrag );
writer.append( blockQuote, docFrag );
writer.append( p2, blockQuote );
writer.insertText( 'foo', p1 );
writer.insertText( 'bar', p2 );
return docFrag;
} );
editor.model.insertContent( docFrag );
In this example, we create the necessary elements (paragraph
and blockQuote
) using the createElement()
method from the editor.document
object. Then, we insert these elements into the editor’s content using the insertContent()
method. Finally, we append p2
to the blockQuote
element.
The resulting HTML structure will be:
<paragraph>foo</paragraph>
<blockQuote>
<paragraph>bar</paragraph>
</blockQuote>
Hi Rizwan,
Nice piece of code!
Are you familiar with CKEditor5 widget to encapsulate several paragraphs into a block widget?
Thanks.
Rgds.
Jerome
Hi Jerome,
Recently, I had done lot of customization in ckeditor, can you exactly tell how you want paragraphs in the widget, so I can tell you exactly.