![](/img/trans.png)
[英]how to use querySelectorAll on the added nodes in a MutationObserver
[英]How do I use the MutationObserver to check for an element with class being added to body?
我发现 MutationObserver 文档相当混乱。 我想观察文档正文何时将具有 class superelement
元素的 DIV 元素添加到 DOM。
<div class="superelement" style="display:none;2"></div>
我设法将这个片段粘合在一起:
const observer = new MutationObserver(onMutation);
observer.observe(document, {
childList: true,
subtree: true,
});
function onMutation(mutations) {
const found = [];
for (const { addedNodes } of mutations) {
for (const node of addedNodes) {
if (!node.tagName) {
continue; // not an element
} else {
if (node.classList.contains('superelement')) {
console.log(node)
}
}
}
}
}
有没有更简洁的方法来迭代所有添加的元素? 我可以想象这是相当缓慢的。
在找到一些不是一团糟的东西之前,我不得不进行一些搜索。 你真的只需要做两件事; 当您有干净的代码可以使用时,它会容易得多。
第一个MutationObserver
object 将传递一个MutationRecord
object 和一个MutationObserver
{childList: true}
(没有第三个参数)当条件满足时(在这种情况下:
const observer = new MutationObserver(function(mutation_record,mutation_observer)
{
//Match your condition here:
if (mutation_record[0] && mutation_record[0].addedNodes[0] && mutation_record[0].addedNodes[0] === id_('modal'))
{
//Do a jig.
}
});
要开始观察,只需将节点定义为第一个参数和包含条件的 object:
observer.observe(tag_('body')[0], {childList: true});
在这里做一些快速研究是第二个参数 object 的详尽示例:
{
attributes: false,
attributeOldValue: false,
//attributeFilter: array,
characterDataOldValue: false,
childList: true,
characterData: false,
subtree: false,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.