Reputation: 33
I am trying to detect html element which is loaded from 3rd party library for example: div with title "box". It should should be detected without using delays.
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");
}
Upvotes: 3
Views: 170
Reputation: 371203
If you know where the element is going to be appended, you can attach a MutationObserver to the parent, which will run a callback when a child is appended:
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 });
If you don't know where the element is going to be appended, but you can identify the element (such as with a selector), you can still use a MutationObserver, but it'll have to watch for deep changes via subtree: true
, which can be expensive on large pages which change a lot:
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>
Upvotes: 5