'How to set cursor position in contenteditable div without random span

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?



Solution 1:[1]

Given a quad like:

pD ---- pC
|       |
|       |
|       |
pA ---- pB

You can get a random point by getting a random point within that normalized square and use the A-to-B and A-to-D vectors as a coordinate basis.

In practice:

// gets a value between 0.0 and 1.0
float randomVal();

vec3 point_in_quad(vec3 pA, vec3 pB, vec3 pC, vec3 pD) {
  return pA + (pB - pA) * randomVal() + (pD - pA) * randomVal();
}

Solution 2:[2]

If you assume convexity, you can do it with:

// gets a value between 0.0 and 1.0
float randomVal();

vec3 point_in_quad(vec3 pA, vec3 pB, vec3 pC, vec3 pD) 
{
    vec3 ab =  pA + (pB - pA) * randomVal();
    vec3 dc =  pD + (pC - pD) * randomVal();
    vec3 r =  ab + (dc - ab) * randomVal();
    
    return r;
}

Basically, pick two randoms points. One on AB and one on CD. Then pick a point randomly in between those two.

Credits to @frank for the framework.

For uniformly random point on the quad, see:

Random points inside a parallelogram

This question is badly named. The answer applies to any quad.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2