Detective jquery div from specific class added to DOM

I use .on() to bind the div events that are generated after the page loads. It works fine for click, mouseenter ... but I need to know when a new div of class MyClass was added. I am looking for this:

 $('#MyContainer').on({ wascreated: function () { DoSomething($(this)); } }, '.MyClass'); 

How should I do it? I managed to write an entire application without a plugin, and I want to save it that way.

Thank.

+57
jquery
May 02 '12 at 14:05
source share
5 answers

After 3 years of experience, I listen to the "element of a specific class added to the DOM": you just add a hook to the jQuery html() function, for example:

 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 use jQuery, which is what I do. And it does not depend on the browser-specific DOMNodeInserted event, which is not cross-browser compatible. I also added the same implementation for .prepend()

All in all, it works like a charm for me, and hopefully for you too.

+7
May 20 '15 at 19:57
source share

Previously, you could connect to the jQuery domManip method to catch all the jQuery dom manipulations and see what elements were inserted there, etc., but the jQuery team closed this in jQuery 3.0+, since this is usually a bad solution to connect to jQuery methods like this way, and they did it, so the domManip internal method domManip no longer available outside jQuery core code.

The mutation events are also outdated, since earlier it was possible to 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 will work as follows

 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); 
+65
May 02 '12 at 14:17
source share

Here is my plugin that does this: jquery.initialize

Usage is the same as the .each function, but with the .initialize function on the element, unlike .each - it will also initialize elements added in the future without any additional code - regardless of whether you added this with AJAX or something else.

Initialization has the same syntax as with .each function

 $(".some-element").initialize( function(){ $(this).css("color", "blue"); }); 

But now, if a new element appears on the page that matches the .some-element selector, it will be instantly initialized. The way to add a new item is not important, you do not need to worry about any callbacks, etc.

 $("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color! 

Plugin based on MutationObserver

+29
Feb 04 '15 at 1:03
source share

After considering this and several other posts, I tried to distill what, in my opinion, was the best of all, into something simple, which allowed me to detect when a class of elements was inserted, and then act on these 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); }); 

It is important to note that this allows: a) the target element to exist at any depth in the “added Nodes” and b) the ability to deal with the element only during initial installation (there is no need to search the entire document or ignore the “already processed” flags).

+7
Jul 22 '16 at 3:08
source share

you can use mutation events

http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents

EDIT

from MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events

Deprecated This feature has been removed from the Internet. Although some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or web applications using it can be interrupted at any time.

Mutation observation is a proposed replacement for mutation events in DOM4. They should be included in Firefox 14 and Chrome 18.

https://developer.mozilla.org/en/docs/Web/API/MutationObserver

MutationObserver provides developers with the ability to respond to changes in the DOM. It is intended to replace mutation events defined in the DOM3 Events specification.

Usage example

The following example was taken from http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/ .

 // select the target node var target = document.querySelector('#some-id'); // create an observer instance var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log(mutation.type); }); }); // configuration of the observer: var config = { attributes: true, childList: true, characterData: true }; // pass in the target node, as well as the observer options observer.observe(target, config); // later, you can stop observing observer.disconnect(); 
+5
May 2 '12 at 14:15
source share



All Articles