无法通过chrome扩展编辑DOM元素

问题描述 投票:0回答:1

我正在开发 chrome 扩展,我需要将我的元素插入另一个元素中。第一个 console.log 输出 HTML 集合,但第二个 console.log 输出空数组。我尝试调用priceBlock[0],但结果为空。我有一个 MutationObserver,用它我可以确保这个元素不会改变。

    document.addEventListener("DOMContentLoaded", () => {
        const priceBlock = document.getElementsByClassName("price-block");
        const paragraph = document.createElement("p");
        console.log(priceBlock);
        console.log(Array.from(priceBlock), "arr");
        paragraph.textContent = "Your text";
        Array.from(priceBlock).forEach((element) => {
            element.appendChild(paragraph);
        });
    });
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const observer = new MutationObserver((mutationsList, observer) => {
        for (let mutation of mutationsList) {
            if (mutation.target.classList.contains("price-block")) {
                const abobusElement = document.createElement("p");
                abobusElement.textContent = "Abobus";
                mutation.target.appendChild(abobusElement);
            }
        }
    });
    observer.observe(document.body, { subtree: true, childList: true });

我尝试询问chatGPT

javascript dom google-chrome-extension
1个回答
0
投票

我的 MutationObserver 写得不正确,因此没有注意到更改。这是正确的选项:

const observer = new MutationObserver((mutationsList, observer) => {
    for (let mutation of mutationsList) {
        if (mutation.type === "childList") {
            const addedNodes = mutation.addedNodes;
            for (let node of addedNodes) {
                if (node.classList && node.classList.contains("price-block")) {
                    const abobusElement = document.createElement("p");
                    abobusElement.textContent = "Abobus";
                    node.appendChild(abobusElement);
                    console.log("Элемент price-block появился в DOM");
                    observer.disconnect();
                    break;
                }
            }
        }
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.