I have a JavaScript function that should be executed only when an element of a certain id becomes available in the DOM.
Following the documentation to produce a working example was non trivial, and the DOM documentation can provide useful clarification.
It turned out the MutationObserverInit dictionary
was not an "object type" but just an Interface Description Language (IDL) term used to describe an options object for observing changes - an Object object is all that is required.
FWIW here's an example of detecting adding a new node with, or changing the id of an existing node to, "certainId".
"use strict";
const target = document.getElementById("target");
const observer = new MutationObserver( checkChanges);
const certainId = "certainId";
function checkChanges(changeList, fromObserver) {
console.log("Callback 2nd argument is the observer object: %s", fromObserver === observer);
for( let change of changeList) {
if( change.type == "attributes") {
if( change.target.id === certainId) {
console.log("id has been changed: ", change.target);
break;
}
}
else if( change.type == "childList") {
for( let node of change.addedNodes) {
if( node.id==certainId) {
console.log("target was added: ", node);
break;
}
}
}
}
}
observer.observe( target, {
subtree: true,
attributeFilter: ["id"],
childList: true
});
// test
function changeId() {
if( document.getElementById("test1")) {
test1.id = "certainId";
}
}
function insertSpan() { // button click
if( document.getElementById("test2")) {
test2.innerHTML = '<span id="certainId">span#certainId<\/span>';
}
}
<div id="target">
<div id="test1">
div#test1 (oriinally)
</div>
<div id="test2">
div#test2
</div>
</div>
<button type="button" onclick='changeId()'>Set id value</button> OR
<button type="button" onclick="insertSpan()">insert new element</button>
It is possible to click both test buttons in the snippet and produce elements with duplicate ids - best avoided in practice.