Home > Net >  Why can I console.log() the html of a node, but MutationObserver fails to recognise it?
Why can I console.log() the html of a node, but MutationObserver fails to recognise it?

Time:09-28

Im trying to use MutationObserver on a <div> but am getting the error:

jquery.min.js:2 Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'

indicating the MutationObserver cannot find the node or is loading before the node appears (which is strange as the div is just a normal part of the DOM - not added dynamically).

However if I do:

console.log($("#myDiv").html());

before my MutationObserver script it returns the divs html, as expected.

I'm curious as to why this is?

My full code:

$( document ).ready(function() {
    console.log($("#myDiv").html());
    const container = $("#myDiv");
    const options = { childList: true };
    
    const observer = new MutationObserver(function onMutation(mutations, observer) {
      console.log('Mutations', mutations)
    });
    
    observer.observe(container, options);
});

CodePudding user response:

MutationObserver is a native javascript feature, so won't understand jquery objects.

Changing

const container = $("#myDiv");

to

const container = $("#myDiv")[0];

or using observer.observe(container[0], options);

will convert the jquery object to the native javascript node which can then be used by the MutationObserver.

  • Related