Home >Web Front-end >JS Tutorial >How to Insert HTML into a Contenteditable DIV at the Caret Position?
Challenge:
In a contenteditable div, keypress events capture can be used to prevent entering text when the Enter key is pressed. With the cursor in the desired insertion point, we seek a method to insert HTML (e.g., a
tag) without having it displayed as plaintext.
Solution:
While using Range.pasteHTML() works in IE, other browsers display the HTML tag as text. The following function allows us to insert HTML in all major browsers, replacing existing text if selected:
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(); // Create a document fragment from the HTML string var el = document.createElement("div"); el.innerHTML = html; var frag = document.createDocumentFragment(); while ((node = el.firstChild)) { frag.appendChild(node); } range.insertNode(frag); // Preserve the selection after the inserted content if (frag.lastChild) { 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); } }
Enhanced Functionality (August 2013):
In response to user requests, an additional parameter has been added to specify whether or not the inserted content should be selected.
function pasteHtmlAtCaret(html, selectPastedContent) { // Similar functionality as the original function // ... }
This updated function allows us to control the selection behavior after inserting HTML content.
The above is the detailed content of How to Insert HTML into a Contenteditable DIV at the Caret Position?. For more information, please follow other related articles on the PHP Chinese website!