Q:

Javascript in Chrome extension to replace certain characters

I'm using an extension called Weboverride to modify the formatting on a support site I use daily.  Here is an example of the content I'm trying to replace:
<div class="longdesc"><pre style="clear:both;word-wrap:break-word;white-space:pre-line;">Update by Beeson,Scott via the web. 

this is a web test

<test type="test">
 Content
</test>
</pre></div>

The browser renders it like this:

this is a web test   
Content

I'm using the following javascript in the weboverride extension in an attempt to replace < and > with &lt; and &gt; in hopes that it will render properly:
(function () {    
    var nodes = document.getElementsByClassName("longdesc");
    for (var n=0; n<nodes.length; n++) {
        var node = nodes[n].getElementsByTagName("pre");
        node[0].textContent = node[0].textContent.replace("<", "&lt;");
    }
})();

Instead, it makes the code look like this:
<div class="longdesc"><pre style="clear:both;word-wrap:break-word;white-space:pre-line;">Update by Beeson,Scott via the web. 

this is a web test

 Content

</pre></div>

It seems to just strip out everything and I really don't understand why, especially since I haven't added the > replacement yet.  How can I do this properly?

A:

you're using textContent which strips HTML tags out. Use innerHTML instead.
Example: https://jsfiddle.net/rdw6904n/2/
(function () {    
    var nodes = document.getElementsByClassName("longdesc");
    for (var n=0; n<nodes.length; n++) {
        var node = nodes[n].getElementsByTagName("pre");
        if (node.length > 0) {
            node[0].innerHTML = node[0].innerHTML.replace(/</g, "&lt;");
        }
    }
})();

I also added in a check to make sure your node array has objects in it before trying to access the first one. Not performing this check could cause your script to crash because you'd be trying to access a property (innerHTML/textContent) on undefined (node[0])
Also, I replaced your call to .replace with replace(/</g, "&lt;") the /g here means global, so it will replace all instances which match < as opposed to just the first one.

