0

Suppose I am having a DOM structure like this,

<body>
    <!-- Dom elements -->

    <div class="red"></div>
    <div class="red"></div>
    <div class="red"></div>

    <!--More Dom elements -->
</body>

You can see there are three elements with class= red. Now suppose of because some user activity two more elements are added to DOM like below.

<body>
    <!-- Dom elements -->

    <div class="red"></div>
    <div class="red"></div>
    <div class="red"></div>

    <div class="red"></div> <!--New element added because of some user activity -->
    <div class="red"></div> <!--New element added because of some user activity -->

    <!--More Dom elements -->
</body>

Now i want some mechanism that whenever news elements get added to DOM they report to a function.

Below is a hypothetical function iam looking for

jQuery('.red').onAddedToDom_AfterDomReady(function(){
               //do something to all added elemnents
               //like bind some events to them etc
});

Is there any existing feature in jQuery that iam missing or any plugin that may help!!

Praveen Prasad
  • 31,561
  • 18
  • 73
  • 106
  • possible duplicate of [Is there a jQuery DOM change listener?](http://stackoverflow.com/questions/2844565/is-there-a-jquery-dom-change-listener) – karim79 Jul 18 '11 at 13:48
  • just checked this answer, its not what iam looking for!! – Praveen Prasad Jul 18 '11 at 13:56
  • Sounds like the code should trigger an event when new elements are added. Just listen for the event and you know what action to take when fires. – epascarello Jul 18 '11 at 15:13

3 Answers3

0

This would rely on the DOMNodeInserted event which is not supported in IE.

See related question for IE support

Basically you have to periodically poll the DOM for any new elements and that's rather expensive.

Community
  • 1
  • 1
Raynos
  • 166,823
  • 56
  • 351
  • 396
0

Try using .live() method of jQuery. It works on limited events of future matching elements. API link.

Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
0

Instead of just adding a <div> element, if you have a widget and if you insert them, then u can have a 'onattach' handler on that widget

Creating a jquery widget - http://www.erichynds.com/jquery/tips-for-developing-jquery-ui-widgets/ . It shows that there is a _create method that can be overridden to do what you want when the widget is being created. So you can replace the div class red tags with a widget and have a _create method

Kasturi
  • 3,335
  • 3
  • 28
  • 42