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 badges2 Answers
Reset to default 13The 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 MutationRecord
s.
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
版权声明:本文标题:javascript - Watch DOM for new elements (VanillaJS) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741273178a2369578.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论