简体   繁体   English

使用JS替换DOM中的html

[英]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.我正在尝试替换 DOM 中的电话号码,而与它在 DOM 中的写入位置无关。 I have done something similar in jQuery successfully using this code:我使用此代码成功地在 jQuery 中做了类似的事情:

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.现在的问题是,在重新设计网站后,电话号码周围并不总是有一个具有相同 class 或 id 的 div。 So I need to figure out a way to check in every div for the phone number and replace it.所以我需要找到一种方法来检查每个 div 中的电话号码并替换它。 The tricky part is that I can only use JS vanilla at the moment.棘手的部分是我目前只能使用 JS vanilla。

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.我发现的每个解决方案都只会更改整个 html 或添加一些内容,但我找不到有关如何仅更改电话号码的提示。

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使用 jQuery 可以使用$("element:contains(phonenumbergoeshere)")但如果您需要依赖 Vanilla JS,只需遍历所有元素,然后在每个元素的 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.获得元素后,您可以使用String.replace()方法将其替换为您的新电话号码,或者您想要的任何内容,将其设置为新的 innerHTML。

Hope that helps!希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM