Search code examples
javascripthtmlpre

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


I have a text <pre id="printed-table">bunch of monkeys</pre>. I want to process the text with a javascript window.onload to highlight the word monkeys.

So, it should look like

bunch of monkeys
when page is loaded.

I have a script

<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>

But when the page loads it looks like

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

What am I missing?

Thank you.


Solution

  • Try setting p.innerHTML instead of p.firstChild.nodeValue. If you do, you'll set the actual HTML contents of the element instead of the (text) value of the text node inside the <pre> element.

      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>