1

I'm trying to dynamically add some CSS classes to some elements that I don't have control over the creation of. I know that the divs I'm looking for will be added like this: mydiv.appendChild(resdiv). However, I cannot add code at that point at which they're created. I know that every instance of this div that is dynamically added will have a specific CSS class (let's call it output-class). I could theoretically add CSS rules to that specific class, but I'd rather not - it would result in the duplication of a lot of styles.

What I want to do is fire an event as soon as a div with the output-class class is added to the page. I'm trying to add some more CSS classes on the fly. Here's what I have so far:

jQuery('body').on('DOMNodeInserted', ".output-class", function(event) {
    var el = $(this);
    el.addClass('my new class');
    // do some more manipulation of the new div (el).
});

However, as far as I can tell, this callback is never called. What am I doing wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Isaac Dontje Lindell
  • 3,246
  • 6
  • 24
  • 35
  • Might this help? http://stackoverflow.com/questions/6814219/jquery-use-element-with-domnodeinserted – DevlshOne Jul 18 '13 at 15:13
  • If your DOM elements are being added via an AJAX request success/complete callback, you can set up a global ajaxComplete event handler that checks for those elements being added. – Derek Jul 18 '13 at 15:14
  • Could help : http://jsfiddle.net/gabrieleromanato/XaTCh/ – sdespont Jul 18 '13 at 15:20
  • Golly gee @DevlshOne! I already had a tab with that answer open, and I just skimmed it instead of actually reading it :(. That did it. If you make it an answer I'll accept. (Thanks to @sdespont too, that was also the right answer). – Isaac Dontje Lindell Jul 18 '13 at 15:25

1 Answers1

4

There are several related question involving DOM Insertion including this one which contains the following code:

document.addEventListener("DOMNodeInserted", function(event) {
    alert($(event.target).parent()[0].tagName);
});
Community
  • 1
  • 1
DevlshOne
  • 8,357
  • 1
  • 29
  • 37