开发者

Basic find replace words

开发者 https://www.devze.com 2023-03-10 19:42 出处:网络
All I want is to replace several words to other words. I tried the following but it conflicts and breaks other elements of the site such as AJAX elements etc.

All I want is to replace several words to other words. I tried the following but it conflicts and breaks other elements of the site such as AJAX elements etc.

document.body.innerHTML = document.body.innerHTML.开发者_如何学JAVAreplace(/searchword/g, "resultword");

I'm also pretty sure this is a fairly non-elegant way to do this when just doing this for multiple words in a big list. Thanks.


Starting at the parent element that contains all the text you are searching (up to the body), replace the text in each text node.

If you have a huge page with many replacements you may need to break it up with a timer, or hide the parent element until all the replacements are done. Otherwise you will get a page redraw for every change.

function replaceText(node, find, rep){
    if(node){
        node= node.firstChild;
        while(node!= null){
            if(node.nodeType== 3){
                node.data= node.data.replace(find, rep);
            }
            else{
                if(node.hasChildNodes()) replaceText(node, find, rep);
            }
            node= node.nextSibling;
        }
    }
    return true;
}

replaceText(document.body,/e/g,'E')


I would use something like the following example

Recursively Loop Through All Nodes

and then check its nodeType. If its == 3 it means its a text node, then just do a replace on the nodeValue of the node.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号