英文:
Dynamically replace < and > with < and >
问题
我尝试创建一个简单的JS函数,动态替换<pre>
元素中的<
和>
为&lt;
和&gt;
。为什么它不起作用?
let pres = document.querySelectorAll('pre');
for (let pre of pres) {
pre.textContent = pre.textContent.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
稍后编辑:我实际想要实现的是,当我打开一个网页时,<pre>
元素应该以HTML标记的文字形式显示,即:
<!-- this is how html works! -->
foo <strong>bar</strong>
英文:
I try to make a simple JS function to dynamically replace <
and >
inside pre
elements with &lt;
and &gt;
. Why it doesn't work?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let pres = document.querySelectorAll('pre');
for (pre in pres) {
pre.textContent = pre.textContent.replace('<', '&lt;');
pre.textContent = pre.textContent.replace('>', '&gt;');
}
<!-- language: lang-html -->
<pre>
foo <strong>bar</strong>
</pre>
<!-- end snippet -->
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>
答案1
得分: 2
<
是 HTML 中的特殊字符。它代表标签的开始,而不是文本中的大于号。
因此,你的 HTML 中在 textContent
中没有任何 <
,只存在于 innerHTML
中:
for (const pre of document.querySelectorAll('pre')) {
pre.textContent = pre.innerHTML;
}
<pre>
foo <strong>bar</strong>
</pre>
英文:
<
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
:
<!-- begin snippet: js hide: false console: true babel: null -->
<!-- language: lang-js -->
for (const pre of document.querySelectorAll('pre')) {
pre.textContent = pre.innerHTML;
}
<!-- language: lang-html -->
<pre>
foo <strong>bar</strong>
</pre>
<!-- end snippet -->
答案2
得分: 1
另一种方法是将 <
和 >
替换为 &lt;
和 &gt;
,将其存储在 result
中,然后将其包装在 code
标签中,并将其分配回 pre
元素。
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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
<!-- language: lang-html -->
<pre>
foo <strong>bar</strong>
</pre>
<!-- end snippet -->
英文:
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.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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
<!-- language: lang-html -->
<pre>
foo <strong>bar</strong>
</pre>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论