admin管理员组

文章数量:1278652

I'm working on a Chrome extension, which parses the DOM and transforms some text nodes based on certain criteria. I am using pure Javascript, i.e. no jQuery or another framework, and I want to keep it that way.

How can I watch the DOM for new dynamically inserted elements, so I can run my parser on them too?

Again, please don't suggest any jQuery solutions, or solutions using anything but pure Javascript.

I'm working on a Chrome extension, which parses the DOM and transforms some text nodes based on certain criteria. I am using pure Javascript, i.e. no jQuery or another framework, and I want to keep it that way.

How can I watch the DOM for new dynamically inserted elements, so I can run my parser on them too?

Again, please don't suggest any jQuery solutions, or solutions using anything but pure Javascript.

Share Improve this question asked Dec 23, 2015 at 6:28 minimlminiml 1,5392 gold badges17 silver badges27 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

The accepted answer actually doesn't work, for a couple of reasons (explained below).

Instead, I would suggest this:

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    mutation.addedNodes.forEach(function(addedNode) {
      // Do things to `addedNode` here
    });
  });
});

observer.observe(document.body, {childList: true, subtree: true});

...because, as miniml correctly points out, subtree: true is required to receive events for elements added that aren't direct children, and the arguments passed to the listener callback is an array of MutationRecords.

Also, I've chosen document.body as my observation root since I don't think listening for elements dynamically inserted into <head> is something most people are interested in. (But if that is desired, then just replace document.body with document.documentElement or just document.)

Fun side note: in the accepted answer, the only time that listener would ever actually fire at all would be if someone literally removed the <html> element and/or re-created it afterward. That's it. (Because the document object is only allowed to have one Element child.)

If you are targeting modern browsers, then you should be using Mutation Observers. To do something when new node is inserted into the document, you would have code:

var domInsertionObserver = new MutationObserver(function(mutation){
  for (var node = 0; node < mutation.addedNodes.length; node++) { 
    //do what you need to do with the added nodes
  }
});
domInsertionObserver.observe(document, { childList: true });

本文标签: javascriptWatch DOM for new elements (VanillaJS)Stack Overflow