Replace text in website with Chrome content script extension

I took the example from JavaNut13 and Matt Curtis to create an alias hider extension for Reddit, and updated it for the new manifest 2. It looks for user on Reddit named "user1" and replaces it with "nobody". Modify as you need.

manifest.json

{
  "name": "No Alias",
  "version": "0.1",
  "permissions": [
    "https://www.reddit.com/*"
  ],
  "content_scripts": [
    {
      "matches": ["https://www.reddit.com/*"],
      "js": ["myscript.js"],
      "run_at": "document_end"
    }
  ],
  "manifest_version": 2
}

myscript.js

document.body.innerHTML = document.body.innerHTML.replace(new RegExp("user1", "g"), "nobody");

I have actually written this in jQuery: (Making sure you have the correct include tag)

var replaced = $("body").html().replace(/text/g,'replace');
$("body").html(replaced);

Replacing/changing text within the DOM on this scale should not be done with blunt HTML-regex replacement, which is very unsafe. You risk mutilating the HTML in the process.

What you need to do is loop over every TextNode (Node) within the document, modifying the text within them.

Your code will end up looking something like this:

var replaceTextInNode = function(parentNode){
    for(var i = parentNode.childNodes.length-1; i >= 0; i--){
        var node = parentNode.childNodes[i];

        //  Make sure this is a text node

        if(node.nodeType == Element.TEXT_NODE){
            node.textContent = /* modify text here */
        } else if(node.nodeType == Element.ELEMENT_NODE){
            //  Check this node's child nodes for text nodes to act on

            replaceTextInNode(node);
        }
    }
};

replaceTextInNode(document.body);

Use the DOM and modify the data of the appropriate Text nodes. E.g.

document.body.querySelector(".number").firstChild.data = "dos";