简体   繁体   中英

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:

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 !

Does someone have an idea ? :)

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.

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

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