I have a parent node in my dom. I have to call a method when a specific element is inserted in the parent node (newly inserted node is not a direct child, its a subtree, may be present at 2/3 level deep).
I have a code for single element insertion which works as expected
var parentNode = jQuery('.parent-node');
var observer = new MutationObserver(function (mutations) {
if (parentNode.find('.sub-class-1')[0] !== undefined) {
//call method
this.disconnect();
}
}).observe(parentNode[0], {childList:true, subtree: true });
But i want to execute callbacks for multiple sub elements creations. i tried this by using forEach on sub-class elements array.
arr.forEach(function (ob) {
new MutationObserver(function (mutations) {
if (parentNode.find(ob.className)[0] != undefined) {
//ob.callback()
this.disconnect();
}
}).observe(parentNode[0], { attributes:false, childList: true, subtree: true });
});
But after processing one subclass, it does not processes the rest subclasses. I guess we can only create on object on particular node. So, how to detect all this nodes on creation to execute specific callbacks using MutationObserver or is there any better alternative approach.
Hi please try this,
var config = { attributes: true, childList: true, characterData: true };
var observers = [];
function createObserver(target, index) {
var observer = new MutationObserver(function(mutations) {
var $this = this;
mutations.forEach(function(mutation) {
if (parentNode.find('.sub-class-1')[0] !== undefined) {
$this.disconnect();
}else{
observers.push($this);
}
});
});
observer.observe(target, config);
}
$('.parent-node').each(function(i, el) {
createObserver(el, i)
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.