MutationObserver behavior after item deletion

I have MutationObserverone associated with an #foohtml element .

var target = document.querySelector("#foo");
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        // ...
    });
});

When the user clicks on an item #button, it #foois deleted and reappears after a second.

<div id="button">Click me to remove the Foo!</div>
<div id="foo">Hello, I'm Foo!</div>

And as I noticed, after removal and recreation, the #fooobserver stopped working.

  • Is this normal behavior?
  • So, do I need to start the observer again?

And the third question:

  • Is the first observer completely remote? Or, instead, is it still working, just "doing nothing"? “I ask about this because I do not want several observers to work if only one of them did the real work.”
+4
source share
1

, .

id, , : observer.observe , , - , . DOM , , , , :

var target = document.querySelector("#foo");
var observer = new MutationObserver(function(mutations) {
    snippet.log("#foo was modified");
});
observer.observe(target, {subTree: true, childList: true});
var counter = 0;
tick();
setTimeout(function() {
  snippet.log("Replacing foo with a new one");
  target.parentNode.removeChild(target);
  target = document.createElement("div");
  target.id = "foo";
  target.innerHTML = "This is the new foo";
  document.body.insertBefore(target, document.body.firstChild);
}, 1000);
function tick() {
  target.appendChild(document.createTextNode("."));
  if (++counter < 20) {
    setTimeout(tick, 200);
  }
}
<div id="foo">This is the original foo</div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script>
Hide result

, DOM, , , , :

var target = document.querySelector("#foo");
var observer = new MutationObserver(function(mutations) {
    snippet.log("#foo was modified");
});
observer.observe(target, {subTree: true, childList: true});
var counter = 0;
tick();
setTimeout(function() {
  snippet.log("Removing foo for a moment");
  target.parentNode.removeChild(target);
  setTimeout(function() {
    snippet.log("Putting the same foo back in");
    document.body.insertBefore(target, document.body.firstChild);
  }, 100);
}, 1000);
function tick() {
  target.appendChild(document.createTextNode("."));
  if (++counter < 20) {
    setTimeout(tick, 200);
  }
}
<div id="foo">This is the original foo</div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.imtqy.com/simple-snippets-console/snippet.js"></script>
Hide result

, , observe.


, :

, ?

, :

observer.disconnect();

, :

observer.observe(theNewElement, /*...options go here...*/);

? , , , " "?

, , , , , , , . , , observer disconnect , , . , . , .

, , , .

"", . , . , , . , , .

+5

Source: https://habr.com/ru/post/1627661/


All Articles