2

I want to call a function over specific elements on my DOM, for example:

$(".red").css({backgroundColor: "pink"});

It works ok for any element already existing into the DOM, but I also want to this method to be called in elements dynamically added to the DOM.

I've tried things like:

$(".red").on(function(){ this.css({backgroundColor: "pink"}) });

or:

$(".red").on("load", function(){ this.css({backgroundColor: "pink"}) });

But not any success.

Check the jsFiddle

Update

The .css() call is just an example I actually want to call other kind of functions

fguillen
  • 36,125
  • 23
  • 149
  • 210

2 Answers2

7

You were close. Try:

$(document).on("load", ".red", function(){ this.css({backgroundColor: "pink"}) });

Oops, that doesn't work. This does http://jsfiddle.net/4Bv9r/

$('body').on('DOMNodeInserted', ".red", function(){ $(this).css({backgroundColor: "pink"}) });
fguillen
  • 36,125
  • 23
  • 149
  • 210
Barbara Laird
  • 12,599
  • 2
  • 44
  • 57
  • 1
    this doesn't work. http://jsfiddle.net/22kwt/2/ paragraph tags don't have a load event. – Kevin B Sep 05 '13 at 19:01
  • Just a note, `DOMNodeInserted` doesn't work on IE8 and below. – j08691 Sep 05 '13 at 19:08
  • If you need to do IE, look at onreadystatechange and/or propertychange events. http://stackoverflow.com/questions/2143929/domnodeinserted-equivalent-in-ie & http://stackoverflow.com/questions/15018590/domnodeinserted-in-the-ie – Barbara Laird Sep 05 '13 at 19:18
  • 1
    @fguillen And if you want to support newer browsers since `DOMNodeInserted` is deprecated, you can use a `MutationObserver`: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver . You can detect support and fallback to older methods – Ian Sep 05 '13 at 19:20
1

If you know the element is going to be added dynamically, the best way should be adding the rules to a stylesheet.

OR you can create style dynamically,

$("<style>").text(".red { background-color: pink; }").appendTo("head");

OR

Add this in your page <style id='d_style'></style> then

$('#d_style').text(".red { background-color: pink; }");
rAjA
  • 899
  • 8
  • 13