Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restore Node/Element after it has been modified/removed from DOM

I am in need of a way to detect if any DOM Node/Element has been removed or modified and instantly restore that element to the state in which it was before.

I tried to "backup" the body node and set the body.innerHTML to its original state every time MutationObserver is fired after the first run but that crashes the browser.

Is there any fast way to restore elements that have been modified or removed?

like image 465
SpoonGuy Avatar asked Oct 20 '22 00:10

SpoonGuy


1 Answers

This is all I can come with (a bit hacky, but it works). Click test or test #2 for removing nodes: http://codepen.io/zvona/pen/BowXaN?editors=001

HTML:

<div class='preserve'>
  <h1>There can be anything inside this</h1>
  <p>Some content</p>
</div>

<div class='preserve'>
  <p>Some more content</p>
</div>

JS:

var preserved = document.querySelectorAll('.preserve');
var config = { attributes: true, childList: true, characterData: true };

var createFragment = function(elem, i) {
  var frag = document.createElement('div');
  var id = 'id-'+ new Date().getTime() +'-'+ i;
  frag.setAttribute('id', id);
  elem.parentNode.insertBefore(frag, elem);
  elem.dataset.frag = id;
  observer.observe(elem.parentNode, config);
}

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (!mutation.addedNodes.length && mutation.removedNodes.length) {
      Array.prototype.forEach.call(mutation.removedNodes, function(elem) {
        var frag = document.querySelector('#'+ elem.dataset.frag);
        frag.parentNode.replaceChild(elem, frag);
        createFragment(elem, frag.id.split('-')[2]);
      });
    }
  });
});

Array.prototype.forEach.call(preserved, function(preserve, i) {
  createFragment(preserve, i);
});

If you want to preserve all the nodes (aka document.querySelectorAll('*');), then I think it becomes very heavy from performance point of view.

like image 91
Samuli Hakoniemi Avatar answered Oct 21 '22 17:10

Samuli Hakoniemi