JS replaces only text without html tags and codes

I want to replace some words of a document without changing any html tags or js codes.

Basically what I do

document.body.innerHTML = document.body.innerHTML.replace('lorem','new lorem');

But this code will replace any "lorm". I want to avoid such labels; <script... var lorem = 123; <div class="lorem", <a id="lorem"etc.

How can I do this in JS?

0
source share
2 answers

Go through the DOM and .replace()text node values.

function walk(el, fn) {
    for (var i = 0, len = el.childNodes.length; i < len; i++) {
        var node = el.childNodes[i];
        if (node.nodeType === 3)
            fn(node);
        else if (node.nodeType === 1 && node.nodeName !== "SCRIPT")
            walk(node, fn);
    }
}

walk(document.body, function(node) {
    var text = node.data.split("foo"),
        parent = node.parentNode,
        i = 1,
        newNode;

    parent.insertBefore(textNode(text[0]), node);

    for (; i < text.length; i += 2) {
        (newNode = document.createElement("b"))
                           .appendChild(textNode("bar"));
        parent.insertBefore(newNode, node);
        parent.insertBefore(textNode(text[i]), node);
    }
    parent.removeChild(node);
});

function textNode(txt) {
    return document.createTextNode(txt);
}
+4
source

Another way to do this is to use regular expressions, science you cannot embed HTML tags in node text.

First I use regular expressions to catch parts of the body.innerHTML property that are outside of the HTML tags.

, , .

, , .

, "foo".

:

document.body.innerHTML=document.body.innerHTML.replace(/<[^(script)][^>]*>[^<]*(foo)[^<]*</g,function(match){ return match.replace(/foo/,"newWord"); });

0

All Articles