In an effort to remove attributes added by a 3rd party library from my webapp at runtime, I have been using the code provided below:
document.addEventListener('DOMNodeInserted', () => {
const elements = document.querySelectorAll('[aria-owns]');
elements.forEach(element => {
element.removeAttribute('aria-owns')
})
})
However, a recent error in the console states:
[Deprecation] Listener added for a 'DOMNodeInserted' mutation event. Support for this event type has been removed, and this event will no longer be fired. See for more information.
The reason being that DOMNodeInserted
is no longer recommended for performance reasons and will soon be obsolete. The solution proposed is to use MutationObserver
instead.
However, it is noted that MutationObserver
does not expose Elements
, only nodes.
My attempt at addressing this issue is as follows:
const observer= new MutationObserver(mutationList =>{
mutationList.forEach(mutationRecord => {
const elements= document.querySelectorAll('[aria-owns]');
elements.forEach(element =>
element.removeAttribute('aria-owns')
)
})
});
observer.observe(document, {
childList: true,
subtree: true,
attributeFilter: ['aria-owns']
};
However, there is concern over the redundancy of getting all elements in the document with
document.querySelectorAll('[aria-owns]')
and then individually iterating over them to remove the attribute, when mutationRecod
already provides access to the nodes that have just mutated and contain the desired attribute.
Is there a way to access the element
from the node
s yielded by the MutationObserver
?
Or what is the correct method to edit the attributes of nodes with a MutationObserver
?