0

I have a MutationObserver attached and I am getting mutation events. I can manually look through the events and see the node I am interested in being added and removed. However, I am having difficulty finding this information programmatically.

However, I believe I am close...

handleMutations( mutationsList, observer ) {
    // console.log( mutationsList );
  
    mutationsList.forEach( mutation => {
        mutation.addedNodes.forEach( node => {
            console.log( "added", node, typeof( node ) ) 

            let foundNode = ( node.id === "thediv" );
    
            if ( !foundNode ) {
              const child = node.querySelector( "#thediv" );
      
              if ( child ) {
                foundNode = true;
              }           
            }
    
            if ( foundNode ) {
              console.log( "found node. do something." );
            }
        });         
    }); 
},

The node I am interested in has the id thediv.

The problem is that I get nodes like:

added <!----> object

and I cannot call querySelector on it -- when I do, it simply crashes.

I am sure this is trivial, but how can I be certain I am dealing with a node which responds to querySelector?

James Hudson
  • 844
  • 6
  • 19
  • 2
    When a node has an id, and that id is unique on the page, just use the insanely fast document.getElementById('thediv') inside the observer instead of enumerating the mutations, [example](https://stackoverflow.com/a/38882022). – wOxxOm Oct 20 '21 at 16:49
  • that does appear to be the better solution. – James Hudson Oct 21 '21 at 17:46

0 Answers0