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>
2
Answers
<
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 thetextContent
, only in theinnerHTML
:Another approach by replacing
<
and>
with<
and>
, store it inresult
then wrapped in acode
tag and assigned it back to thepre
element.