In continuation of this issue .

There are two absolutely identical pages. My task is to keep them identical. The problem arises when there is a set of elements with the same selectors, and one of them is deleted. I do not understand how to understand which one. Here is a squeeze of code -

function build_selector(el){ var selector=null; if(el.id){ selector='#'+el.id; }else{ if(el.className){ selector='.'+el.className.split(' ').join('.'); }else{ selector=el.tagName; if(el.name){ selector+='[name='+el.name+']'; } } } if(!selector)console.error('Cant build selector!',el); var index=$(selector).index(el);//Т.к. элемента уже нет в DOM, индекс == -1 if(index==-1)console.error('Smth wrong with:',selector,el); return { selector: selector, index: index } } var target = document.querySelector('html'); observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation){ var target=build_selector(mutation.target); target.removed=[]; for(var i=0;i<mutation.removedNodes;i++){ target.removed.push(build_selector(mutation.removedNodes[i])); } }); }); observer.observe(target, { childList: true, subtree: true }); //test setTimeout(function(){ $('.some_class').eq(2).remove(); },1000); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="some_class">1</span> <span class="some_class">2</span> <span class="some_class">3</span> <span class="some_class">4</span> <span class="some_class">5</span> 

This is how I delete elements in the clone (View is the root element, data [i] is the target from the snippet):

 var el=View.find(data[i].selector).eq(data[i].index); for(var j=0;j<data[i].removed.length;j++){ el.find(data[i].removed[j].selector).eq(data[i].removed[j].index).remove(); } 

    1 answer 1

    If you need to get a unique selector for an element, add something like this to your code during the class match phase:

      var siblings = Array.prototype.slice.call(el.parentNode.childNodes, 0); var index = siblings.indexOf(el) + 1; if (index > 1) { selector += ':nth-child(' + index + ')'; } 

    That will add uniqueness to the selector.

    But as for the whole problem you are solving, if I understand it correctly, you should look at:

    1. https://github.com/Matt-Esch/virtual-dom
    2. https://github.com/fouber/page-monitor
    3. https://github.com/tbranyen/diffhtml