Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
contenteditable div is showing raw html instead of rendered html

When I replace the user selection in a contenteditable div using this function below, then the "new" HTML appears as text (raw HTML) instead of rendered HTML in the div.

In other words, the <h2> tag is being inserted as <h2>, so the display is <h2> instead of a "html heading line".

What am I doing wrong?

function replaceWYS() {
  var sel, range;
  if (window.getSelection) {
    sel = window.getSelection();

    selT = window.getSelection().getRangeAt(0);
    replacementText = "<h2>" + selT + "</h2>";

    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();
      range.insertNode(document.createTextNode(replacementText));
    }
  } else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    range.text = replacementText;
  }

}
<div id="wys" contenteditable>
  This is line<br><br> This line should be heading after replacement
  <br><br> Select it and click the replace button
</div>
<p><button onclick="replaceWYS(); return false;"> Replace now </button></p>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

document.createTextNode renders your HTML as text (if you log it you get "<h2>...</h2>" instead of <h2>...</h2>). You can create an HTML element manually.

function replaceWYS() {
  var sel, range;
  if (window.getSelection) {
    sel = window.getSelection();

    selT = window.getSelection().getRangeAt(0);
    const h = document.createElement("h2");
    h.innerText = selT;

    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();
      range.insertNode(h);
    }
  } else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    range.text = replacementText;
  }
}
<div id="wys" contenteditable>
  This is line<br><br> This line should be heading after replacement
  <br><br> Select it and click the replace button
</div>
<p><button onclick="replaceWYS(); return false;"> Replace now </button></p>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!