I’ve been using this code below to remove attributes added by a 3rd party library from my webapp on runtime.
document.addEventListener('DOMNodeInserted', () => {
const elements = document.querySelectorAll('[aria-owns]');
elements.forEach(element => {
element.removeAttribute('aria-owns')
})
})
However recently, we’ve been getting this error in the console:
[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 https://chromestatus.com/feature/5083947249172480
for more information.
The summary is that DOMNodeInserted
shouldn’t be used anymore for performance reasons, and more importantly bc it will stop working in the near future. It links to an article that mentions that using MutationObserver
is the viable option.
However, MutationObserver
doesn’t expose Elements
, just nodes.
This is what I tried:
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']
};
but if I understand correctly how MutationObserver
works, then it feels like an overkill to get all the elements in the document with document.querySelectorAll('[aria-owns]')
then iterate over them one by one to remove the attribute, if mutationRecod
already yields a collection of the nodes that have just mutated and contain the attribute I am looking for.
is there a way to access the element
from the node
s yielded by the MutationObserver
?
or what is the correct way to edit the attributes of the nodes with a MutationObserver
?