[英]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.