I'm interested in using MutationObserver
to detect if a certain HTML element is added anywhere in an HTML page. For example's sake, I'll say that I want to detect if any <li>
's are added anywhere in the DOM.
All the MutationObserver
examples I've seen so far only detect if a node is added to a particular container. For example:
some HTML
<body>
...
<ul id='my-list'></ul>
...
</body>
MutationObserver
definition
var container = document.querySelector('ul#my-list');
var observer = new MutationObserver(function(mutations){
// Do something here
});
observer.observe(container, {
childList: true,
attributes: true,
characterData: true,
subtree: true,
attributeOldValue: true,
characterDataOldValue: true
});
So in this example, the MutationObserver
is setup to watch a very certain container (ul#my-list
) to see if any <li>
's are appended to it.
Is it a problem if I wanted to be less specific, and watch for <li>
's over the entire HTML body like this:
var container = document.querySelector('body');
I know it works in the basic examples I've setup for myself... But is it not advised to do this? Is this going to result in poor performance? And if so, how would I detect and measure that performance issue?
I figured maybe there was a reason that all the MutationObserver
examples are so specific with their targeted container... but I'm not sure.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…