简体   繁体   中英

Javascript Replace Text in tags without changing children element HTML and Content

I have a script where I'd like to recolocar the text anywhere in the body visible to the user like so:

$("body").html($("body").html().replace(/replaced word/g,'HELLO'));

This works but it works to well. Whenever "replaced word" is within a tag, like a href, or span, or div, or anything it throws off all the formatting on the page. What is the best way to accomplish replacing the text for every occurrence in the page, no matter what element it's in, without effecting the page's functionality? Thanks

EDIT: Thanks to talsibony and everyone's help I have an answer on how to replace words in child elements not effecting the html tags. I'd like to have the replacement with a font color or other styling options like so:

$(element).html($(element).selectorText().replace(/thisi/g,'<abbr title="hover title"><font color="#10a9cf">HELLO</font></abbr>'));

The weird thing is this code works in jsfiddle but when I include this in the google chrome extension I'm working on and the page loads the page is empty. When I switch it back to selectortext it loads but I see the html tags in the replacement.

I can't understand why because a staright replace doesn't work and doesn't let the page load either!

$(element).html($(element).selectorText().replace(/thisi/g,'HELLO'));

In the console I get the following error: Cannot read property 'replace' of null

What am I missing here? Thanks again!

The way I think you will have to do it is in each element individually and use this jquery small plugin I rewrite here is the code and also

fiddle

the html

<div id="parent">
    thisi sthe fpcd
    <p>p</p>
</div>

plugin to find the content of the selector text without child elements

$.fn.selectorText = function(text) {
    var str = '';

    this.contents().each(function() {
        if (this.nodeType === 3) {
            if(text){
                this.textContent = text;
                return false;
            }else{
                str += this.textContent || this.innerText || '';
            }

        }
    });

    return str;
};

using it for your case

allowReplaceTags = ['DIV'];
$('body').find('*').each(function (i, element) {
    if ($.inArray(allowReplaceTags,element.tagName)){
        // do replace
        $(element).selectorText($(element).selectorText().replace(/thisi/g,'HELO'));

    }

});

$(“ body”)。html($(“ body”)。text()。replace(/ replaced word / g,'HELLO'));

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