0

I have a <span contenteditable="true">. When I move to a new line after a list or a table, I get

<div><br></div>

so to get new paragraph instead, I replace the div using

myContentEditableElement.addEventListener('keyup', function(){
    if(this.innerHTML.indexOf('<div><br></div>') != -1) {
        this.innerHTML = this.innerHTML.replace(/<div><br><\/div>/g,'<p><br></p>');
    }
});

Now the caret moves to the start of my contenteditable element. But I need it leaves at its current position i.e. inside of the new paragraph.

I've tried

var range = document.createRange();
range.selectNodeContents(this);
var selection = window.getSelection();
range.setStart(selection.anchorNode, selection.anchorOffset);
selection.removeAllRanges();
selection.addRange(range);

but it doesn't help

stckvrw
  • 1,689
  • 18
  • 42

1 Answers1

0

I have found the answer by myself:

if(~this.innerHTML.indexOf('<div><br></div>')) {
    var newLine = document.createElement('p');
    newLine.innerHTML = '<br>';
    var selection = window.getSelection();
    var newDivNode = selection.anchorNode;
    this.insertBefore(newLine, newDivNode);
    this.removeChild(newDivNode);
    var range = document.createRange();
    range.setStart(newLine, 0);
    range.setStart(newLine, 0);
    selection.removeAllRanges();
    selection.addRange(range);
}
stckvrw
  • 1,689
  • 18
  • 42