Insert div in contenteditable

211 Views Asked by At

I'm trying to insert div with text to contenteditable and select the text between the div tags after adding the div:

div.innerHTML +='<div id="id">selecttext</div>'

but this won't select the selecttext

<html>
    <head></head>
    <body>
        <div id="contenteditable" contenteditable></div>
        <script>
            var contenteditable = document.getElementById("contenteditable");

            contenteditable.onkeyup = function (e) {
                contenteditable.innerHTML += '<div>Start here</div>';
            }
        </script>
    </body>
</html>
1

There are 1 best solutions below

0
On

Your question has three parts:

  1. Insert div with text to contenteditable:
contenteditable.innerHTML += '<div id="startHere">Start Here</div>';
  1. Find startHere div:
function findStartHereDiv(contenteditable) {
    var childNodes = contenteditable.childNodes;
    for(var i = 0; i < childNodes.length; i++) {
        if(childNodes[i].id == 'startHere') {
            return childNodes[i];
            break;
        }
    }
   return null; 
}
  1. Select text of startHere div:
function selectText(element) {
    var doc = document
        , text = doc.getElementById(element)
        , range, selection
    ;    
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();        
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

Is this what you need?

DEMO