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>