4

I know this question may be asked before but I did not find the correct answer that works.

I tried this code

$('body *').each(function(k,v){$(v).text($(v).text().replace("Hazem","mizzo"))});

but the page crashes, I don't know why.

I'm prefer the code to be in pure javascript not jQuery. Thanks.

Hazem Taha
  • 1,154
  • 6
  • 18
  • 31
  • 1
    Possible duplicate of [javascript replace text in the html body](http://stackoverflow.com/questions/5558613/javascript-replace-text-in-the-html-body) – Manasov Daniel Jan 01 '16 at 19:29
  • 1
    @ManasovDaniel: That's a duplicate indeed, but gives a terrible solution. –  Jan 01 '16 at 19:32
  • Add a `Hazem` to all the instances where you have the string you want to replace. Then, just use something analogous to `$(".name-to-replace")` (or `document.getElementsByClassName("name-to-replace")` as your selector. – adilapapaya Jan 01 '16 at 19:35

1 Answers1

10

You should walk the DOM, find text nodes, and replace the found text in each.

Here's a simple example. You can make walkText() more generic by passing a callback that does the replacement.

function walkText(node) {
  if (node.nodeType == 3) {
    node.data = node.data.replace(/foo/g, "bar");
  }
  if (node.nodeType == 1 && node.nodeName != "SCRIPT") {
    for (var i = 0; i < node.childNodes.length; i++) {
      walkText(node.childNodes[i]);
    }
  }
}
walkText(document.body);
foo <b>foo</b> foo