Search code examples
replacejqueryreplacewith

How To I Replace New Elements Added To A Page With Jquery


Here is the scenario... I have a a checkbox next to each field that I am replacing on page load with jquery with "Delete" text that enables me to delete the field via jquery, which is working fine. Like so...

$(".profile-status-box").each(function(){ $(this).replaceWith('<span class="delete">' + 'Delete' + '</span>') });

The problem comes in however is that after page load, I am also giving the user the option to dynamically add new fields. The new added fields though have the checkbox and not the delete link because they are not being replaced by jquery since they are being added after the initial page load.

Is't possible to replace the content of new elements added to the page without doing a page refresh? If not, I can always have two templates with different markup depending one for js and one for non js, but I was trying to avoind taht.

Thanks in advance.


Solution

  • You can use the .livequery() plugin, like this:

    $(".profile-status-box").livequery(function(){ 
      $(this).replaceWith('<span class="delete">Delete</span>') 
    });
    

    The anonymous function is run against every element found, and each new element matching the selector as they're added.