javascriptecmascript-6innertext

Dynamically replace < and > with &lt; and &gt;


I try to make a simple JS function to dynamically replace < and > inside pre elements with &lt; and &gt;. Why it doesn't work?

let pres = document.querySelectorAll('pre');
for (pre in pres) {
  pre.textContent = pre.textContent.replace('<', '&lt;');
  pre.textContent = pre.textContent.replace('>', '&gt;');
}
<pre>
foo <strong>bar</strong>
</pre>

Later edit: What I actually want to achieve is that when I open a webpage, pre elements should display HTML markup literally, that is:

<!-- this is how html works! -->
foo <strong>bar</strong>

Solution

  • < is a special character in HTML. It represents the start of a tag, not a greater than sign in the text.

    Consequently your HTML doesn’t have any < in the textContent, only in the innerHTML:

    for (const pre of document.querySelectorAll('pre')) {
      pre.textContent = pre.innerHTML;
    }
    <pre>
    foo <strong>bar</strong>
    </pre>