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>
CodePudding user response:
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>