Home >Web Front-end >JS Tutorial >How to Insert HTML at the Cursor Position in a ContentEditable Div in All Browsers?
Problem Statement
Inserting HTML, such as a
tag, at the cursor position in a contenteditable div is desired. While the answer provided in a previous question successfully accomplishes this task in IE using Range.pasteHTML(), other browsers display the inserted HTML as plain text.
Solution
To insert HTML directly into browsers other than IE, utilize the insertNode() method of the Range object:
function pasteHtmlAtCaret(html) { var sel, range; if (window.getSelection) { // IE9 and non-IE sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { range = sel.getRangeAt(0); range.deleteContents(); var el = document.createElement("div"); el.innerHTML = html; var frag = document.createDocumentFragment(), node; while (node = el.firstChild) { frag.appendChild(node); } range.insertNode(frag); range = range.cloneRange(); range.setStartAfter(frag.lastChild); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } else if (document.selection && document.selection.type != "Control") { // IE < 9 document.selection.createRange().pasteHTML(html); } }
Updated Solution with Option to Select Pasted Content
Optionally, you can select the inserted content using an extra parameter:
function pasteHtmlAtCaret(html, selectPastedContent) { // ... Original code ... var firstNode = frag.firstChild; range.insertNode(frag); if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); if (selectPastedContent) { range.setStartBefore(firstNode); } else { range.collapse(true); } sel.removeAllRanges(); sel.addRange(range); } // ... Original code ... }
This code provides cross-browser compatibility for inserting HTML at the cursor position, with the added flexibility of selecting the inserted content if desired.
The above is the detailed content of How to Insert HTML at the Cursor Position in a ContentEditable Div in All Browsers?. For more information, please follow other related articles on the PHP Chinese website!