在网页中查找“旧”的所有实例,并使用javascript bookmarklet将每个实例替换为“new”

问题描述:

我想要做的是用JS书签或者creammonkey脚本中的'new'替换网页中'old'的所有实例。我怎样才能做到这一点?我认为jQuery或其他框架是可以的,因为它们都包含在bookmarklet和greasemonkey脚本中。

What I want to do is replace all instances of 'old' in a webpage with 'new' in a JS bookmarklet or a greasemonkey script. How can I do this? I suppose jQuery or other frameworks are okay, as there're hacks to include them in both bookmarklets as well as greasemonkey scripts.

一个防止破坏的功能。这意味着这不会触及任何标签或属性,只会触及文本。

A function that is clobber-proof. That mean's this won't touch any tags or attributes, only text.

function htmlreplace(a, b, element) {    
    if (!element) element = document.body;    
    var nodes = element.childNodes;
    for (var n=0; n<nodes.length; n++) {
        if (nodes[n].nodeType == Node.TEXT_NODE) {
            var r = new RegExp(a, 'gi');
            nodes[n].textContent = nodes[n].textContent.replace(r, b);
        } else {
            htmlreplace(a, b, nodes[n]);
        }
    }
}

htmlreplace('a', 'r');

Bookmarklet版本:

Bookmarklet version:

javascript:function htmlreplace(a,b,element){if(!element)element=document.body;var nodes=element.childNodes;for(var n=0;n<nodes.length;n++){if(nodes[n].nodeType==Node.TEXT_NODE){nodes[n].textContent=nodes[n].textContent.replace(new RegExp(a,'gi'),b);}else{htmlreplace(a,b,nodes[n]);}}}htmlreplace('old','new');