Source Code:
(back to article)
Submit
Result:
Report an issue
<div id="editable" contenteditable="true" style="border: 1px solid #ccc; padding: 10px; min-height: 50px;"> Click here and set the cursor position. </div> <button onclick="insertText()">Insert 'Hello World'</button> <script> function insertText() { const editableDiv = document.getElementById('editable'); const sel = window.getSelection(); // Check if the selection is within the editable div if (!sel.rangeCount || !editableDiv.contains(sel.getRangeAt(0).commonAncestorContainer)) return; const range = sel.getRangeAt(0); range.deleteContents(); // Clears any selected text const textNode = document.createTextNode('Hello World'); range.insertNode(textNode); range.setStartAfter(textNode); range.setEndAfter(textNode); sel.removeAllRanges(); // Clear the previous selection sel.addRange(range); // Re-select the new text node } </script>