提问人:Даниил Ельчуков 提问时间:10/30/2023 更新时间:10/30/2023 访问量:28
无法通过 chrome 扩展程序编辑 DOM 元素
Can't edit DOM element by chrome extension
问:
我正在开发 chrome 的扩展,我需要将我的元素插入另一个元素中。第一个控制台 .log 输出一个 HTML 集合,但第二个控制台输出一个空数组。我尝试调用 priceBlock[0],但结果是 null。我有一个 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
答:
0赞
Даниил Ельчуков
10/30/2023
#1
我的 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;
}
}
}
}
});
评论
css
.price-block::after { content: "your text" }