5

What I want to do is replace all instances of 'foo' in a webpage with 'bar' in a JS bookmarklet/greasemonkey script. How can I do this? I suppose jQuery works, as there're hacks to include those in both bookmarklets and greasemonkey scripts.

  • 1
    "Not trying to be lazy" - guess it comes to you without effort! Make your title a short summary with enough information to help people would be interested find your question; provide the details in the body. – Jay Bazuzi Jul 20 '09 at 19:22
  • Could you please give an example of what a good way to split it up might be? Sorry, new to this! –  Jul 20 '09 at 19:24

1 Answers1

13

This script iterates through each element in the document and replaces every instance of foo with bar.

The gi modifiers on the regex make it do a global, case-insensitive search.

var els = document.getElementsByTagName("*");
for(var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  el.innerHTML = el.innerHTML.replace(/foo/gi, 'bar');
}

You can target specific tag names by changing the "*" to the tag name of your choice (e.g. "p", "td").

mwfearnley
  • 3,303
  • 2
  • 34
  • 35
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
  • 3
    Why not just `document.body.innerHTML.replace(/foo/gi, 'bar');`? Grabbing all of the elements as you suggest can cause recursive replacement when elements are nested. – ændrük Sep 02 '12 at 23:18
  • 1
    @ændrük should be ``document.body.innerHTML = document.body.innerHTML.replace(/foo/gi, 'bar')``. See [Comment](http://stackoverflow.com/a/29316601/1933185). – jerik Mar 02 '17 at 08:19
  • 4
    Modifying innerHTML, which inculdes each element's children, is a very bad advice because it'll break lots/most of pages that use addEventListener and element references. Use TreeWalker API: [Replace many text terms, using Tampermonkey, without affecting URLs and not looking for classes or ids](//stackoverflow.com/a/24419809) – wOxxOm Jul 15 '17 at 10:59
  • I wonder what compels people to take the time comment on (and try to "correct") accepted answers from over eight years ago. Truly bizarre. – Josh Stodola Jul 20 '17 at 22:10
  • 3
    Probably because it's a valid criticism, and this is the first result in Google for certain terms, making it rather important. – Leagsaidh Gordon Jul 28 '17 at 15:55
  • That's why I'm here! This is exactly what I was looking for and it was the first Bing result. – CXL Aug 05 '20 at 16:30