Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery detecting div of certain class has been added to DOM

Tags:

jquery

I'm using .on() to bind events of divs that get created after the page loads. It works fine for click, mouseenter... but I need to know when a new div of class MyClass has been added. I'm looking for this:

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

How do I do this? I've managed to write my entire app without a plugin and I want to keep it that way.

Thanks.

like image 495
frenchie Avatar asked May 02 '12 14:05

frenchie


People also ask

How do you check if a class is added in jQuery?

The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

Which method is triggered when an element is added to Dom?

The actual answer is "use mutation observers" (as outlined in this question: Determining if a HTML element has been added to the DOM dynamically), however support (specifically on IE) is limited (http://caniuse.com/mutationobserver). So the actual ACTUAL answer is "Use mutation observers....

How can I replace one class with another in jQuery?

To replace a class with another class, you can remove the old class using jQuery's . removeClass() method and then add the new class using jQuery's . addClass() method.


2 Answers

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); 
like image 77
adeneo Avatar answered Sep 19 '22 11:09

adeneo


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

like image 41
Adam Pietrasiak Avatar answered Sep 21 '22 11:09

Adam Pietrasiak