Search code examples
javascriptdommutation-observers

Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'


I am creating a script for adding attributes for some elements. And I want it to work for the dynamically added elements. I wanted to use Mutation Observe, but I got this error: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

The code I use:

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
});

And I really don't know if I did everything right. Please help me if you find a mistake


Solution

  • The code in the question works correctly, I only needed to remove the last line in the code (observer.disconnect()) and I am very grateful for the help of @wOxxOm, who helped to rework the callback.