简体   繁体   中英

Replace html in DOM using JS

I am trying to replace a phone number in the DOM independently of where it is written in the DOM. I have done something similar in jQuery successfully using this code:

jQuery(document).ready(function($){

     function changePhoneNumbers (phoneContainer) {
    for (var i = 0; i < phoneContainer.length; i++) {
        if (jQuery(phoneContainer[i]).length > 0) {
            replaceFallbackNumber(phoneContainer[i]);
        }   
    }
}
function replaceFallbackNumber (container) {
    var oldNrs = [
        "0123 123456",
        "0123 123456",
    ];
    var newNr = "0231 177293-79";
    for (var i = 0; i < oldNrs.length; i++) {
        jQuery(container).html(jQuery(container).html().replace(oldNrs[i], newNr));
    }
}
var phoneContainer = [
    '.gglenumber',
    '.about_gastrohero',
    '.booklet'
];
changePhoneNumbers(phoneContainer);

});

The thing is now, that after reworking the website the phone number does not always have a div around it with the same class or id. So I need to figure out a way to check in every div for the phone number and replace it. The tricky part is that I can only use JS vanilla at the moment.

Every solution I find only changes the whole html or adds something to but I can't find a hint on how to only change the phone number and nothing else.

Does anybody have any idea or hint on how to solve this? Here are some example containers

<span class="gglenumber">0231 123456</span> 

<a href="tel:0231 123456" class="link gglenumber">0231 123456</a>

Well with jQuery you would have been able to use the $("element:contains(phonenumbergoeshere)") but if you need to rely on Vanilla JS, simply loop through all of the elements, and search for the phone number as a string in each element's innerHTML

for (var i = 0; i < document.all.length; i++) {
if (document.all[i].innerHTML.search("phonenumbergoeshere") != -1) {
    var elementWithNumber = document.all[i];
    elementWithNumber.innerHTML = elementWithNumber.innerHTML.replace("oldphonenumber", "newphonenumber");
}
}

Once you get the element, you can use the String.replace() method to replace it with your new phone number, or whatever it is you'd like, setting that as your new innerHTML.

Hope that helps!

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