Recursively walk the nodes and do a regex replace. Quick and dirty example:
function replaceAllWords(newWord) {
for (var i = 0; i < document.childNodes.length; i++) {
checkNode(document.childNodes[i]);
}
function checkNode(node) {
var nodeName = node.nodeName.toLowerCase();
if(nodeName === 'script' || nodeName === 'style') {return;}
if (node.nodeType === 3) {
var text = node.nodeValue;
var newText = text.replace(/\b\w+/g, newWord);
node.nodeValue = newText;
}
if (node.childNodes.length > 0) {
for (var j = 0; j < node.childNodes.length; j++) {
checkNode(node.childNodes[j]);
}
}
}
}
//Use like
replaceAllWords("Hello");
Doing a regex on innerHtml will replace anything that matches, including any block script thats on the page. This function checks that it is actually a text node, before doing a replace, the replace only does word characters (A-Za-z0-9_) that are 1 or more characters, so will not replace spaces or symbols (i.e. punctuation, $ etc will stay put)
4
solved Javascript: How do I change every word visible on screen? [closed]