skip to Main Content

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>

2

Answers


  1. < 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>
    Login or Signup to reply.
  2. Another approach by replacing < and > with &lt; and &gt;, store it in result then wrapped in a code tag and assigned it back to the pre element.

    let preEl = document.querySelector('pre');
    let specialChars = {
      '<': '&lt;',
      '>': '&gt;'
    }
    let result = '<code>';
    for (let chr of preEl.innerHTML) {
      if (specialChars[chr]) {
        result += specialChars[chr]
      } else {
        result += chr
      }
    }
    result += '</code>';
    preEl.innerHTML = result
    <pre>
    foo <strong>bar</strong>
    </pre>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search