I want to replace a specific word in my code without effecting html URLs and attributes. i tried to replace each p tag but there are some contents in div tags which also needs to be replaced.
$("p:not(:has(img))").each(function(){
    var b = $(this).html().replace(/oldtext/g, "newtext");
    $(this).html(b);  
});
                I wrote a vanilla JavaScript function for you, it doesn't change anything but the oldtext to the newtext:
replaceAllTextWith = function (jq, oldtxt, newtxt) {
    for (var j = 0; j < jq.length; j++) {
        var el = jq[j];
        for (var i = 0; i < el.childNodes.length; i++) {
            var cnode = el.childNodes[i];
            if (cnode.nodeType == 3) {
                console.log(el.tagName);
                var nval = cnode.nodeValue;
                //add .toLowerCase() here if you want to consider capital letters
                if (-1 < nval.indexOf(oldtxt)) {
                    cnode.nodeValue = nval.replace(new RegExp(oldtxt, "g"), newtxt);
                }
            } else if (cnode.nodeType == 1) {
                replaceAllTextWith([cnode], oldtxt, newtxt);
            }
        }
    }
};
you can call it like:
replaceAllTextWith($("p:not(:has(img))"), "oldtext", "newtext")
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With