79kep
79kep

Reputation: 37

How can I make the < and > actually become < and > in an innerText and innerHTML combination to make plain text?

If I have standalone less than signs, greater than signs, or ampersands in the <xmp> replacement using JavaScript, it treats them as &lt; and &gt; and &amp; respectively. I also want to keep HTML escaped entities, but not escape the < and >. Here's the replacement on top and the actual, deprecated <xmp>. That is, if it's even possible.

var a = document.getElementById("xmp").innerHTML;
document.getElementById("xmp").innerText = a
#xmp {
    white-space: pre;
    font-family: monospace;
}
<!-- The JavaScript xmp replacement - it doesn't show the greater than sign properly as it is entity escaped. I also need to keep the entities normal without being unescaped. -->
<div id="xmp">Foo bar              foo bar <a>this is xmp. &lt;</a> ></div>
  <!-- what <xmp> is like - DON'T USE THIS! -->
  <xmp>Foo bar              foo bar <a>this is xmp. &lt;</a> ></xmp>

Upvotes: 1

Views: 582

Answers (1)

vanowm
vanowm

Reputation: 10201

I think you are confused here, you can't have an unescaped < or > inside of HTML. Your <div> is not valid HTML and browser simply escapes these tags for you

var a = document.getElementById("orig").innerHTML;
document.getElementById("xmp").innerText = a;
document.querySelector("xmp").innerHTML = a;

var clone = document.getElementById("orig").cloneNode(true);
document.querySelector("xmp:nth-of-type(2)").appendChild(clone);
body
{
  white-space: pre;
}
div {
    white-space: pre;
    font-family: monospace;
}
original html:

<div id="orig">Foo bar              foo bar <a>this is xmp. &lt;</a> ></div>

text from original html:

<div id="xmp"></div>

HTML copy from original into &lt;XMP&gt;:
<xmp></xmp>
original clone appended into &lt;XMP&gt;:
<xmp></xmp>
&lt;XMP&gt; with hard coded (invalid html) text:
<xmp>Foo bar              foo bar <a>this is xmp. &lt;</a> > (invalid HTML)</xmp>

Upvotes: 2

Related Questions