When you click on a button, a block (with the contenteditable attribute) is placed in the name and wrapped in element b and then you need to type after the name, if you then click in this block, the cursor does not extend beyond the b element and you get all the printed text in bold too, How to display the cursor for this item?

Why the selectionStart does not work.

<p style=" padding: 10px; background: white; width: 50%;" contenteditable="true" class="write-comment"></p> 

 var formComment = document.querySelector('.write-comment'); var userNameHtml = document.createElement('b'); userNameHtml.innerHTML = userName + ',&nbsp;'; formComment.appendChild(userNameHtml); formComment.focus();formComment.selectionStart = formComment.innerHTML.length; 

    3 answers 3

    As an option, the rest of the text to make a separate element:

     var userName="Vovan"; var formComment = document.querySelector('.write-comment'); var userNameHtml = document.createElement('b'); userNameHtml.innerHTML = userName + ','; var otherText = document.createElement('span'); otherText.innerHTML="&nbsp;"; formComment.appendChild(userNameHtml); formComment.appendChild(otherText); formComment.childNodes[1].selectionStart = 0; formComment.childNodes[1].focus(); 
     <p style=" padding: 10px; background: white; width: 50%;" contenteditable="true" class="write-comment"></p> 

      As an alternative:

       function go() { var formComment = document.querySelector('.write-comment'); var userNameHtml = document.createElement('b'); var emptyNode = document.createTextNode(' '); userNameHtml.contentEditable = false; userNameHtml.innerHTML = "NAME" + ',&nbsp;'; formComment.appendChild(userNameHtml); formComment.appendChild(emptyNode); var range = document.createRange(); var sel = window.getSelection(); range.setStartAfter(emptyNode); range.collapse(false); sel.removeAllRanges(); sel.addRange(range); } 
       <p style=" padding: 10px; background: white; width: 50%;border:1px solid black;" contenteditable="true" id="write-comment" class="write-comment"></p> <button onclick="go()">GO</button> 

         let button = document.querySelector('#button').addEventListener('click', function(){ let formComment = document.querySelector('.write-comment'); let userName = 'Vasia' let range = document.createRange(); formComment.focus() let selection = window.getSelection() range.selectNodeContents(formComment); let userNameHtml = document.createElement('b'); let space = document.createTextNode(' ') formComment.insertBefore(space,userNameHtml.nextChild) userNameHtml.textContent = userName range.insertNode(userNameHtml) let newRange = document.createRange(); range.selectNodeContents(formComment) range.collapse() selection.removeAllRanges() selection.addRange(range) selection.collapseToEnd(); }) 
         .write-comment{ white-space: pre; } 
         <p style=" padding: 10px; background: white; width: 50%; " contenteditable="true" class="write-comment"></p> <button id='button'>click</button>