How to replace all occurrences of a string in a HTML page using Javascript

醉酒当歌 提交于 2020-12-31 15:46:19

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/34559256/how-to-replace-all-occurrences-of-a-string-in-a-html-page-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!