метод замены не работает в браузере, но работает в console.log - PullRequest
1 голос
/ 20 марта 2019

Я пытаюсь заменить несколько вхождений на веб-сайте 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);
    }
};

Как ни странно, метод замены прекрасно работает в console.log (я вижу, что тестовое слово было удалено), но ничего не изменилось на странице browser !

У кого-нибудь есть идея? :)

ArbreMojo.

1 Ответ

1 голос
/ 20 марта 2019

Вы просто обновляете значение переменной, чтобы оно не обновляло фактическое содержимое элемента. Чтобы заставить его работать, обновите содержимое элемента, просто обновив свойство textContent.

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