ポール:
タイトル「ボックス」とDIV:私は、例えば、サードパーティのライブラリからロードされたHTML要素を検出しようとしています。これは、遅延を使用せずに検出されなければならない必要があります。
function createBox() {
var parser = new DOMParser();
var domString =
'<div title="box" style="border:solid" class="container"><button>btn</button><span class="intro">Hello</span> <span id="name"> World!</span></div>';
var html = parser.parseFromString(domString, "text/html");
document.body.append(html.body.firstChild);
}
setTimeout(function() {
// Do something after 2 seconds
createBox();
}, 2000);
let box = document.querySelector('[title="box"]');
if (box != null) {
console.log("box is detected");
}
CertainPerformance:
あなたは要素が追加されようとしている場所を知っていれば、子が追加されたときにコールバックを実行する親へのMutationObserverを添付することができます。
function createBox() {
var parser = new DOMParser();
var domString =
'<div title="box" style="border:solid" class="container"><button>btn</button><span class="intro">Hello</span> <span id="name"> World!</span></div>';
var html = parser.parseFromString(domString, "text/html");
document.body.append(html.body.firstChild);
}
console.log('start');
setTimeout(function() {
// Do something after 2 seconds
createBox();
}, 2000);
new MutationObserver(() => {
const box = document.querySelector('[title="box"]');
if (box) {
console.log("box is detected");
}
})
.observe(document.body, { childList: true });
あなたがいる場合していない要素が追加されようとしている場所を知っていますが、(例えば、セレクタのように)要素を識別することができ、あなたはまだMutationObserverを使用することができますが、それは経由深い変更を監視する必要がありますsubtree: true
どの缶、多くのことを変更する大規模なページに高価なもの:
console.log('start');
function createBox() {
var parser = new DOMParser();
var domString =
'<div title="box" style="border:solid" class="container"><button>btn</button><span class="intro">Hello</span> <span id="name"> World!</span></div>';
var html = parser.parseFromString(domString, "text/html");
outer.append(html.body.firstChild);
}
setTimeout(function() {
// Do something after 2 seconds
createBox();
}, 2000);
new MutationObserver((_, observer) => {
const box = document.querySelector('[title="box"]');
if (box) {
console.log("box is detected");
observer.disconnect();
}
})
.observe(document.body, { childList: true, subtree: true });
<div id="outer">outer</div>