从脚本更新时如何在 <pre> 中使用 html 标签

How to use html tags in <pre> when updated from the script

我有一条短信<pre id="printed-table">bunch of monkeys</pre>。我想用 javascript window.onload 处理文本以突出显示单词 monkeys.

因此,加载页面时它应该看起来像

bunch of monkeys

我有脚本

<script type="text/javascript">
  window.onload = function() {
    var p = document.getElementById("printed-table");
    var t = p.firstChild.nodeValue;
    p.firstChild.nodeValue = t.replace(/monkeys/gmi, function(a) {
return "<strong>" + a + "</strong>"; } ) } 
</script>

但是当页面加载时看起来像

bunch of &lt;strong&gt;monkeys&lt;/strong&gt;

我错过了什么?

谢谢。

尝试设置 p.innerHTML 而不是 p.firstChild.nodeValue。如果这样做,您将设置元素的实际 HTML 内容,而不是 <pre> 元素内文本节点的(文本)值。

  window.onload = function() {
    var p = document.getElementById("printed-table");
    var t = p.firstChild.nodeValue;
    p.innerHTML = t.replace(/monkeys/gmi, function(a) {
      return "<strong>" + a + "</strong>"; } ) } 
 <pre id="printed-table">bunch of monkeys</pre>