我正在开发 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
我的 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;
}
}
}
}
});