简体   繁体   中英

Replacing Specific Text in a page

I am trying to replace a specific snippet of text inside a paragraph. I am just trying to replace the phone number. The code inside the body i am unable to access due to it being pushed to us via our partner.

To see what options are available please contact a lodging specialist via calling 866.264.1842.

I have tried

$("body").html(
    $("body").html().replace(/866.264.1842/g,'888.888.4754') );

This works however it breaks other code on our page and makes our calendar picker not work. Is there a way just to do this with css. I have access to the CSS but not the JS that is running on the page.

Let's assume the phone number is in a div which ID is "contact". Then you have to do that:

$("#contact").html($("#contact").html().replace(/866.264.1842/g,'888.888.4754'))

That way you don't remove the DOM modifications made by your calendar picker javascript code.

I have rewritten a function for this, hopefully this should work for you

function replaceDOMText(str, replaceWith) {
    $('body:contains(' + str + ')').contents().each(function() {
        if (this.nodeType == 3) {
            $(this).parent().html(function(_, oldValue) {
                return oldValue.replace(RegExp(str, "g"), replaceWith);
            })
        }
    });
}


// Call like this
replaceDOMText("866.264.1842", "888.888.4754" );

Play with this fiddle

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