jquery detecting div of certain class has been added to DOM
After reviewing this and several other posts I tried to distill what I thought was the best of each into something simple that allowed me to detect when a class of elements is inserted and then act on those elements.
function onElementInserted(containerSelector, elementSelector, callback) {
var onMutationsObserved = function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.addedNodes.length) {
var elements = $(mutation.addedNodes).find(elementSelector);
for (var i = 0, len = elements.length; i < len; i++) {
callback(elements[i]);
}
}
});
};
var target = $(containerSelector)[0];
var config = { childList: true, subtree: true };
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(onMutationsObserved);
observer.observe(target, config);
}
onElementInserted('body', '.myTargetElement', function(element) {
console.log(element);
});
Importantly for me, this allows a) the target element to exist at any depth within "addedNodes" and b) the ability to deal with the element only when initially inserted (no need to search the entire document setting or ignoring "already-processed" flags).
3 years of experience later, this is how I listen to "element of a certain class added to the DOM": you simply add a hook into the jQuery html()
function, like this:
function Start() {
var OldHtml = window.jQuery.fn.html;
window.jQuery.fn.html = function () {
var EnhancedHtml = OldHtml.apply(this, arguments);
if (arguments.length && EnhancedHtml.find('.MyClass').length) {
var TheElementAdded = EnhancedHtml.find('.MyClass'); //there it is
}
return EnhancedHtml;
}
}
$(Start);
This works if you're using jQuery, which I do. And it doesn't rely on the browser-specific event DOMNodeInserted
, which is not cross-browser compatible. I also added the same implementation for .prepend()
Overall, this works like a charm for me, and hopefully for you too.
Here is my plugin that does exacly that - jquery.initialize
Useage is the same like you'd use .each
function, but with .initialize
function on element, difference from .each
is it will also initialize elements added in future without any additional code - no matter if you add it with AJAX or anything else.
Initialize have exacly the same syntax as with .each function
$(".some-element").initialize( function(){
$(this).css("color", "blue");
});
But now if new element matching .some-element selector will appear on page, it will be instanty initialized. The way new item is added is not important, you dont need to care about any callbacks etc.
$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!
Plugin is based on MutationObserver
Previously one could hook into jQuery's domManip
method to catch all jQuery dom manipulations and see what elements where inserted etc. but the jQuery team shut that down in jQuery 3.0+ as it's generally not a good solution to hook into jQuery methods that way, and they've made it so the internal domManip
method no longer is available outside the core jQuery code.
Mutation Events have also been deprecated, as before one could do something like
$(document).on('DOMNodeInserted', function(e) {
if ( $(e.target).hasClass('MyClass') ) {
//element with .MyClass was inserted.
}
});
this should be avoided, and today Mutation Observers should be used instead, which would work like this
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation)
if (mutation.addedNodes && mutation.addedNodes.length > 0) {
// element added to DOM
var hasClass = [].some.call(mutation.addedNodes, function(el) {
return el.classList.contains('MyClass')
});
if (hasClass) {
// element has class `MyClass`
console.log('element ".MyClass" added');
}
}
});
});
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(document.body, config);