在'MutationObserver'上执行'observing'失败:参数1不属于'Node'类型。

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

我正在创建一个为一些元素添加属性的脚本。我希望它能适用于动态添加的元素。我想使用Mutation Observe,但我得到了这个错误。Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

我使用的代码:

const langAdding = (tag) => {
    tag.setAttribute('lang', 'en-us');
}

const target = document

const callback = (mutations, observer) => {
    mutations.forEach(mutation => {
        switch (mutation.type) {
            case 'childList':
                for (const el of mutation.addedNodes) {
                    if (!el.hasAttribute("lang")) {
                        el = langAdding(el) 
                    } else if (el.firstElementChild) {
                        for (const child of el.getElementsByTagName('p')) {
                            child = langAdding(child);
                    }
                }
                break;
        }
    })
}

const observer = new MutationObserver(callback);

observer.observe(target, {
    childList: true,
    attributes: true,
    characterData: true,
    subtree: true
});

我真的不知道我做的一切是否正确。如果你发现错误,请帮助我

javascript dom mutation-observers
1个回答
0
投票

问题中的代码可以正常工作,我只需要删除代码中的最后一行(observer.disconnect()),我非常感谢@wOxxOm的帮助,他帮助我重新设计了回调。

© www.soinside.com 2019 - 2024. All rights reserved.