JSFiddle - React, Tailwind, and code Playground
HTML
<div class="root" contenteditable="true">
<div id="block-1" class="block">Block 1 [Paragraph]</div>
<div id="block-2" class="block">Block 2 [IMG]</div>
</div>
CSS
*,
*::before,
*::after {
box-sizing: border;
}
body {
margin: 0;
}
.root {
max-width: 700px;
margin: 1rem auto;
}
.root:focus {
outline: 0;
}
.block {
font-size: 21px;
line-height: 1.8;
color: rgba(0, 0, 0, .83)
}
.is-focused {
background-color: rgb(240, 254, 255);
}
JavaScript
let
root = document.querySelector('.root'),
old_block = document.querySelectorAll('.block'),
dummy_id = 2;
function placeCursorInRichText(el, selector, start) {
const range = document.createRange();
const sel = window.getSelection();
const sub = el.querySelector(selector);
range.setStart(sub, start ? 0 : sub.childNodes.length);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
root.addEventListener('keydown', (e) => {
if (e.key !== 'Enter')
return;
e.preventDefault();
dummy_id++;
let template =`<div id="block-${dummy_id}" class="block">Block ${dummy_id}</div>`;
root.insertAdjacentHTML('beforeend', template);
placeCursorInRichText(root, `#block-${dummy_id}`);
})