Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda