Home >Web Front-end >JS Tutorial >How to Insert HTML at the Caret in a ContentEditable Div?

How to Insert HTML at the Caret in a ContentEditable Div?

Linda Hamilton
Linda HamiltonOriginal
2024-11-11 07:38:03582browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn