I try to make a simple JS function to dynamically replace <
and >
inside pre
elements with <
and >
. Why it doesn't work?
let pres = document.querySelectorAll('pre');
for (pre in pres) {
pre.textContent = pre.textContent.replace('<', '<');
pre.textContent = pre.textContent.replace('>', '>');
}
<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>
<
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>