HTML – Contenteditable – prevent default behavior on enter and add own behavior

I’m currently working on a feature that adds functionality to the span-tags inside the contenteditable div. The sentences are displayed in the span tags, so I can execute a specific range of functions on each sentence.The sentences are provided by the backend.

Additionally, I want to add the functionality to add new sentences to the contenteditable div. If the user presses enter an new line break and new span element should be created inside the div with the EventListeners the span needs.

Therefore, I need to prevent the contenteditable’s div’s default behavior and add custom behavior.

There is the problem. I can append a new div-tag and inside it aspan-tag with all event listeners. But the cursor isn’t following and the new created span-tag isn’t automatically selected that the input text the user writes is assigned to this span tag. The input text is always added outside the created div.

I tried to do it with window.getSelection and a new range but each time the span and br-element are inserted into the last span as a child element, what shouldn’t be.

enter image description here

This is the current code to it:

if (event.key !== 'Enter') return;

event.preventDefault();

let div = document.createElement('div');
let span = document.createElement('span');

span.addEventListener('mouseover', (event) =>
  this.test(event)
);

span.addEventListener('mouseout', (event) =>
  this.test(event)
);

span.addEventListener('click', (event) =>
  this.test(event)
);

div.appendChild(span);

const selection = window.getSelection();
const range = selection.getRangeAt(0);

range.deleteContents();
range.insertNode(div);

range.setStartAfter(div);
range.setEndAfter(div);

selection.removeAllRanges();
selection.addRange(range);