Using the MutationObserver API, I'm trying to attach events to specific elements when they are loaded into the DOM. Code snippet based on the sample on the spec:
var targetNode = document.getElementById("myDiv");
// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
mutation.addedNodes.forEach(function(currentValue, currentIndex, listObj) {
if (currentValue.querySelectorAll(".questions").length > 0) {
//we added the questions
var elements = document.querySelectorAll(".myList, .ofElements");
//elements is empty here. After the callback fires,
//I can query again and find the elements
elements.forEach(function() {
this.addEventListener("click", function() {alert(this.name + "=" + this.value)});
});
}
});
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, { attributes: false, childList: true });
It's matching .questions
when it gets added as a child node to the DOM, but at this point it's not able to find the inputs.
Am I misunderstanding how this works? Or is it possible that the code which adds .myList, .ofElements
(I cannot modify the source code) is doing something that interferes?