AHMED.D
AHMED.D

Reputation: 165

Replace a text in html tag without effecting tags attributes and links

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);  
});

Upvotes: 5

Views: 759

Answers (2)

Vickel
Vickel

Reputation: 7997

this is an interesting task as jquery's html() displays only the html inside the selector, but not the html of a nested element

the solution is to break down the html code line by line (block) and check if there is a certain element (img) or not, in order to perform the replace.

this is the html:

<div id="a_unique_wrap_id">
<p><img src="https://www.google.pt/images/srpr/logo11w.png" /><h1>abc</h1></p>
<p><img src="https://www.google.pt/images/srpr/logo11w.png" />def</p>
<p><h1><span><b>abc</b></span></h1></p>
<div><h1><span><b>abc</b></span></h1></div>
<div><h1><span><b>def</b></span></h1></div>
</div>

and this is the javascript:

selector=$('div');
exclude='<img';

str=(selector.html().split('\n'));
l=str.length;
output='';
for(x=0;x<l;x++){
    if(str[x].indexOf(exclude)>=0){
        output+=str[x];       
    }else output+=str[x].replace(/abc/g, "newtext");
}
$('#a_unique_wrap_id').html(output);

a working example is here: http://jsfiddle.net/hbrunar/w6BfL/6/

Upvotes: 0

Mehran Hatami
Mehran Hatami

Reputation: 12961

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")

Upvotes: 2

Related Questions