WYSIWYG rich content editor. Part 1. The basics

The aim of these pages is to explain how to create a HTML rich content editor. The goal is to explain step by step how to build the editor. I'll try, as much as possible, to use VanillaJS (pure JS without external framework or libraries).

This first part explains how to create and focus the editor. Here is the result of this first part:

Create the HTML editor

First, create a HTML div and add this attribute: contenteditable="true".

<div id="editor" contenteditable="true"><p>Edit here.</p></div>

Add some CSS

We'll add some simple CSS on our editor:

#editor {
    white-space: pre-wrap;
    background-color: #eaeaff;

We'll also remove the margins on the <p> tag since this tag will be our paragraph separator:

#editor p { margin: 0; }


First we get the editor node:

let editor = document.getElementById('editor');

Then we set the focus when the page is loaded:

document.addEventListener("DOMContentLoaded", function() {


For debugging purpose, I added a new section for displaying the HTML content of the editor :

<pre id="output"></pre>

Everytime the content is changed, the output is updated:

let output = document.getElementById('output');

// Update the output when the editor is updated
document.onselectionchange = () => {
    // Check if the editor is focussed
    if (editor === document.activeElement)
        output.textContent = editor.innerHTML;


Try to update the editor content to see the HTML output:

See also

Last update : 03/29/2020