Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda