views:

117

answers:

2

Is there a way to have a declaration such as the following persist to all matching elements that are later added to the DOM?

$("a.my-class").replaceWith("<span>Replaced</span>");

Something along the lines of...

$("a.my-class").persist().replaceWith("<span>Replaced</span>");

(Persist is a fictitious method, that I hope conveys what I would like to accomplish.)

A: 

The live() method in jquery does something similar but it is for events.

You could possibly use live() and the load event to achieve what you are looking for, something like (untested):

$("a.my-class").live('load',function(){
  $(this).replaceWith("<span>Replaced</span>");
});
Fermin
There is no page reload to base an event off of. DOM elements are being added via AJAX.
jerome
The above adds a load event load to the element you add via AJAX ('a.my-class'), not the page load. As I said tho it's untested.
Fermin
+1  A: 

There isn't a method exactly like what you want, but if the content is being added using the jQuery AJAX methods, you can use this:

$("<div></div>").ajaxSuccess(function(){
   $("a.my-class").replaceWith("<span>Replaced</span>");
});

And this code will run after every successful AJAX request, provided the requests are made using a jQuery $.ajax call (including $.post or $.get). You only need to call this once on your page and it will trigger on any AJAX call made.

If you run into trouble with the replacement happening too soon:

$("<div></div>").ajaxSuccess(function(){
   window.setTimeout( function(){
       $("a.my-class").replaceWith("<span>Replaced</span>");
   }, 250);
});
Doug Neiner