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

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

DDD
Release: 2024-11-11 03:42:02
Original
681 people have browsed it

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

Inserting HTML at the Cursor in a ContentEditable Div

When working with a div that allows editing, you may want to insert HTML directly at the cursor. While methods like insertText() can add plain text, browsers typically display HTML inserted this way as text rather than executing it.

To overcome this limitation, a more elaborate approach is required. One solution involves leveraging the insertNode() method of the Range object. However, IE8 and below rely on pasteHTML().

Implementation

The following function handles HTML insertion across major browsers:

function pasteHtmlAtCaret(html) {
  // Obtain the selection range
  var sel, range;
  if (window.getSelection) {
    // For non-IE browsers
    sel = window.getSelection();
    range = sel.getRangeAt(0);
  } else if (document.selection) {
    // For IE8 and below
    range = document.selection.createRange();
  }

  // Delete existing content in the range
  range.deleteContents();

  // Create an element to hold the HTML
  var el = document.createElement("div");
  el.innerHTML = html;
  
  // Create a fragment to insert
  var frag = document.createDocumentFragment();

  // Loop through elements in the div
  while ((node = el.firstChild)) {
    frag.appendChild(node);
  }
  
  // Insert the fragment into the range
  range.insertNode(frag);

  // Position the caret after the inserted content
  range = range.cloneRange();
  range.setStartAfter(frag.lastChild);
  range.collapse(true);
  if (sel) sel.removeAllRanges();
  if (sel) sel.addRange(range);
}
Copy after login

Improvement

Based on user requests, an updated version with an additional parameter was developed:

function pasteHtmlAtCaret(html, selectPastedContent) {
  // ... (same as before)

  // Modify based on parameter
  if (selectPastedContent) {
    range.setStartBefore(frag.firstChild);
  } else {
    range.collapse(true);
  }

  // Update the selection
  sel.removeAllRanges();
  sel.addRange(range);
}
Copy after login

When set to true, this parameter allows you to select the inserted content upon execution.

The above is the detailed content of How to Insert HTML at the Cursor in a ContentEditable Div?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template