Inserting Custom HTML elements in CKEditor5: A Step-by-Step Guide

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>

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

  1. Hi Rizwan,

    Nice piece of code!

    Are you familiar with CKEditor5 widget to encapsulate several paragraphs into a block widget?

    Thanks.

    Rgds.
    Jerome