0

This question is related to the question What does $ mean in the context of jQuery? I asked recently.

I am asking this question because people just marked my original question as a duplicate without providing an answer to the most important part of the question.

I have the following line of code.

$(document).on('DOMNodeInserted', InspectPage.OnNodeInserted);

Since DOMNodeInserted is deprecated I need to replace this with a MutationObserver.

People helpfully pointed out that $ is an alias for the jQuery method. However, this does not answer my original question.

The Mutation events will be removed from Chrome page contains the following block of code.

// Replacement mutation observer code:  
const observer = new MutationObserver(mutationList =>  
  mutationList.filter(m => m.type === 'childList').forEach(m => {  
    m.addedNodes.forEach(doSomething);  
  }));  
observer.observe(target,{childList: true, subtree: true});

I know from reading the documentation for the MutationObserver: observe() method that target in this case is A DOM Node.

I know from reading the jQuery() page that the method returns "a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string".

Unfortunately, this is not enough information since it does not tell me how to get the target parameter of the MutationObserver: observe() method from $(document).

So, in the hopes that my question will actually be answered this time I am being more precise in exactly what I want to know.

What value do I use for the target parameter of the MutationObserver: observe() method in my case?

Three possibilities come to mind.

  • I am overthinking this and I just need to use document.
  • I need to use $(document).
  • Something else I have not considered.
Benilda Key
  • 2,836
  • 1
  • 22
  • 34
  • The reason it got closed is because the answer is trivially found elsewhere, namely that it's just a convenient alias for the `jQuery` global in any context where another thing hasn't taken the 100% valid JS variable name `$` yet. And if your post had _additional_ questions, then [you know that's not how posts work](/help/how-to-ask), those should have been posted separately from the get-go. As for the mutation observer pattern you're looking for, MDN has [the perfect example to get you started](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#example). – Mike 'Pomax' Kamermans Aug 31 '23 at 18:54
  • 1
    Well, you can look at the [page for `Document`](https://developer.mozilla.org/en-US/docs/Web/API/Document) and see that it is a `Node`, so presumably it would work. You could also use `document.documentElement` if you wanted, which is the next level down in the DOM. You *can't* use `$(document)` because that is a jQuery object, not a `Node`. – Heretic Monkey Aug 31 '23 at 19:08

0 Answers0