简体   繁体   中英

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

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM