In my project, I’m trying to wrap inserting elements in a div with “contenteditable=true”. The idea is that the user can insert this element at any time in the div, including in the middle of a text, following the cursor position as in document.getSelection().getRangeAt(0).startOffset
. Below I show a code example that more or less follows my logic
function insert(text){
let element = '<span>'+text+'</span>';
let textarea = document.getElementById('textarea');
textarea.focus();
let range = document.getSelection().getRangeAt(0);
/*From now on, I should have the code that inserts the "element variable" inside the div in the same position where the user puts the editing cursor, but unfortunately everything I tried gave some kind of error or simply didn't come close*/
}
.textarea{
width: calc(100% - 20px);
height: 200px;
background: #f1f1f1;
padding: 10px;
border-radius: 10px;
margin-bottom: 10px;
}
span{
color: dodgerblue;
}
<div class="textarea" id="textarea" contenteditable></div>
<button onclick="insert('additional text')">Insert</button>