[Greasemonkey] Grab text string in TD

Paul Roub paul at roub.net
Fri Apr 22 14:28:11 EDT 2005


Edward Lee wrote:
> On 4/22/05, Scott R. Turner <srt at aero.org> wrote:
> 
>>   document.body.innerHTML = document.body.innerHTML.replace(/Google/,/Goggle/);
> 
> 
> For me, that replaces "Google Search" with "null Search" but all other
> instances Google remain the same because you didn't say to do a global
> match and you're replacing it with a regular expression /Goggle/
> instead of a string.
> 

Even with that fix, is it what you want?  innerHTML.replace will replace 
tag names, attribute values, and anything else *including* the plain text.

To replace *just* the plain text, the cleanest way I know of is to 
recurse the document, looking for text nodes.  e.g.:

function gmSrText(node, searchFor, replaceWith) {
     if (node.nodeType == 3) // text node
     {
         node.nodeValue = node.nodeValue.replace(searchFor, replaceWith);
     }
     else
     {
         var child = node.firstChild;

         while (child != null)
         {
             gmSrText(child, searchFor, replaceWith);
             child = child.nextSibling;
         }
     }
}


Which, if called as:

         gmSrText(document.body, /google/ig, 'goggle');

Would replace all occurrences of Google (case-insensitive), in *text 
only*, with 'goggle'.

Anyone have a simpler variation of this?

-paul


More information about the Greasemonkey mailing list