Is it possible to observer mutations on a DOM node that doesn't exist yet?
Example:
My app creates a div at some point: <div id="message" data-message-content="foo" data-message-type="bar" />
.
I want to watch for the creation & change of this div.
var mutationObserver = new MutationObserver(function(mutations){
// Some code to handle the mutation.
});
mutationObserver.observe(
document.querySelector('#message'),
{
attributes: true,
subtree: true,
childList: true,
characterData: false
}
);
);
Right now this returns an error since #message
is null (the div hasn't been created yet).
Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
An obvious solution is to watch the body
and check if any of the mutations are the creation of div#Message
, but this seems like a bad idea / or possibly bad for performance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…