Hi all,

I have a text box. When users press enter, it triggers the submit function:

    if(commentContent.is(":focus") && (e.keyCode || e.which) == 13 && !e.shiftKey)

This then prepends the content of the text box into the HTML.


However, when I search for this new element by id and class, it doesn't register. Do I need to tell JS to refresh the DOM so I can find it? I have read some discussions about using .on(), does that mean I need to register an event to listen for prepend events??

I realise this isn't about the DOM updating. I use the following functions to pull up the elements and process their click events:

$('.like').each(function(i, obj){


        var element = $(this);


Obviously since the .each() function loads with the page, it doesn't take into account anything I add dynamically... How can I add the objects I add to the DOM dynamically?

Member Avatar

You may need to use the .on trick for delegated events.


Simply, you have a container (in the original HTML) and you add stuff to it. If you reference the container, it acts as a magic box that allows you to run functions on items that don't exist yet. Not sure if I explained myself properly.


$( "#container" ).on( "click", ".item", function() {
  //do whatever

Yes. Not only did that fix it, but got rid of the .each() function :) Thank you very much!