简体   繁体   English

替换方法在浏览器中不起作用但在 console.log 中起作用

[英]replace method not working in browser but working in console.log

I'm trying to replace multiple occurrences in a Wordpress website, so here's what I did:我正在尝试替换Wordpress网站中的多次出现,所以这就是我所做的:

window.onload = init;

function init()
{
    // get all the divs which have specific class names
    let divElems = 
    document.querySelectorAll(".vc_custom_heading.white.vc_gitem-post-data.vc_gitem-post-data-source-post_title");

    // loop on the divs
    for(let i = 0 ; i < divElems.length ; i++)
    {
        // get the first child of the div : a <h2>
        let titleElem = divElems[i].childNodes[0];
        // get the first child of the title : a <a>
        let linkElem  = titleElem.childNodes[0];
        // get the text content of the link
        let text      = linkElem.textContent;

        // replace the word test by nothing
        text = text.replace(/test/g, '');
        // all the occurrences of test have been removed in the console.log, but not in browser
        console.log(text);
    }
};

But weirdly, the replace method works fine in the console.log (I can see that the test word has been removed), but nothing changed in the browser page !但奇怪的是,replace 方法在console.log 中工作正常(我可以看到测试词已被删除),但在浏览器页面中没有任何变化!

Does someone have an idea ?有人有想法吗? :) :)

ArbreMojo. ArbreMojo。

You are just updating the variable value so it won't update the actual element content.您只是在更新变量值,因此它不会更新实际的元素内容。 To make it work, update the element content by simply updating textContent property.要使其工作,只需更新textContent属性即可更新元素内容。

text = text.replace(/test/g, '');
linkElem.textContent = text;

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

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