Home >Web Front-end >JS Tutorial >How to Insert HTML at the Caret in a ContentEditable Div?
Insert Html at Caret in a Contenteditable Div
In contenteditable divs, capturing keypresses allows you to prevent insertion of unwanted characters. This raises the requirement to directly insert HTML elements, such as a
tag. While the solution provided for text insertion in a contenteditable div works in IE using the range.pasteHTML method, it renders the
tag as plain text in other browsers.
Insert HTML Using insertNode()
In most browsers, you can utilize the insertNode() method of the Range obtained from the selection to insert HTML nodes. IE versions below 9 still support pasteHTML().
Function for Inserting HTML
The following function can be used to insert HTML at the caret in all major browsers:
function pasteHtmlAtCaret(html) { var sel, range; if (window.getSelection) { 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, lastNode; while ((node = el.firstChild)) { lastNode = frag.appendChild(node); } range.insertNode(frag); if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } } else if (document.selection && document.selection.type != "Control") { document.selection.createRange().pasteHTML(html); } }
Update: Selecting Inserted Content
For scenarios where you want to select the inserted content after insertion, the function can be updated with an additional parameter as demonstrated below:
function pasteHtmlAtCaret(html, selectPastedContent) { // Implementation with logic for selecting the inserted content if selectPastedContent is true }
The above is the detailed content of How to Insert HTML at the Caret in a ContentEditable Div?. For more information, please follow other related articles on the PHP Chinese website!