I have a function to modify divs of a specific class, but the problem is these divs are being loaded and unloaded dynamically by a 3rd party WP plugin that I cannot modify, and there are no click actions I can bind to. These divs may appear and disappear at any given point in time, and they come inside a more complex set of elements. The plugin starts by loading one div on page load, and later, on click, it loads other divs into it. These inner divs are timed, and they disappear on timeout, loading another set of divs and so on. The ones I'm trying to modify don't come in the first set on click, so I can't bind to that click.
From my research here on StackOverflow and elsewhere I understand that the old method of using mutation events with something like DOMNodeInserted
is deprecated, and the mutation observer should be used, but I can't get my head around it.
I've tried to adapt two pieces of code I found in answers to other questions here, but it didn't work for me.
The logic I'm using is to watch the first wrapper div that gets loaded on page load .modal-survey-container
, and then, whenever it gets new divs loaded into it, my function should fire if my actual target .msnumericanswer
is present inside the subtree. So far I've tried this:
var $j = jQuery;
$j(document).ready(function callback(records) {
records.forEach(function (record) {
var list = record.addedNodes;
var l = list.length - 1;
for ( ; l > -1; l-- ) {
if (list[l].nodeClass === '.msnumericanswer') {
$j('.msnumericanswer').each(function(i, obj) {
var t = $j(obj).data('tooltip');
$j(obj).prepend('<div class="labels">' + t + '</div>');
});
console.log(list[l]);
}
}
});
setTimeout(5000);
});
var observer = new MutationObserver(callback);
var targetNode = document.querySelectorAll(".modal-survey-container");
observer.observe(targetNode, { attributes: true, childList: true, subtree: true });
This doesn't work and throws two errors in console saying:
ReferenceError: callback is not defined.
TypeError: records.forEach is not a function.
The alternative logic is to catch the creation of my target's parent div .survey_table
, so I also tried this:
var $j = jQuery;
var myElement = $j('.survey_table')[0];
var observer = new MutationObserver(function(mutations) {
if (document.contains(myElement)) {
$j('.msnumericanswer').each(function(i, obj) { //my working jQuery
var t = $j(obj).data('tooltip'); //my working jQuery
$j(obj).prepend('<div class="labels">' + t + '</div>'); //my working jQuery
});
}
});
observer.observe(document, {attributes: true, childList: true, characterData: false, subtree:true});
This doesn't work either, but I see no errors inconsole.
What am I doing wrong here?