I have two divs inside a contenteditable div, like this:
<div contenteditable="true" id="mainDiv">
<div id="div1">Line 1</div>
<div id="div2">Line 2</div>
</div>
and I want to set the cursor at the beginning of "Line 2". I use the following code to do so
function setCursorAtInnerDiv(mainDiv, div2) {
let range = document.createRange();
range.selectNodeContents(div2);
range.collapse(true);
let selection = document.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
When I look at the elements, the divs look just as shown above all the way until this code returns.
Then suddenly the HTML gets messed up like this:
<div contenteditable="true" id="mainDiv">
<div id="div1">Line 1</div>
<span style="font-family: -apple-system...; font-size: 1rem;">Line 2</span>
</div>
(where "..." is a bunch of fonts listed). The end result is that instead of a 'div', I know have a 'span', which means Line 2 does not start on its own line.
Why did my div turn into a span (with a bunch of font stuff in it)? Did Chrome do that? I sure didn't.
How can I set the cursor position without messing up my lines? Is there a "don't ruin my html" flag?