-1

I've been searching around for how to select a dynamically-created (by JQuery) element (in this case, div with class "date"), and keep coming across the .on('click') method. While this works, it seems to only select that div once the page (or containing div #date-container, whichever I have initially) is clicked.

Ideally, right when the .date divs load, I would like to perform some JQuery on them. Is this possible without clicking?

JQuery:

$("#date-container").on("click", ".date", function() {
    $('.date').text( $('.date').text().replace('[', '') );
});

HTML:

<div id="date-container"></div>
user2521295
  • 823
  • 2
  • 12
  • 23
  • You only have to wait until the element has been created to act on it with jquery. What you are finding is event delegation, which is a method for adding event handlers to dynamically created elements before they've been added to the DOM (because `$('.date').click(function(){ ... })` only attaches event handlers to the elements currently in the DOM – Rob M. Feb 19 '16 at 19:19
  • 1
    Possible duplicate of [Event when element added to page](http://stackoverflow.com/questions/7434685/event-when-element-added-to-page) – gfullam Feb 19 '16 at 19:23
  • if you create the element dynamically, you should also be able to do whatever you want right after that. Where and how you create the element? give us your code so we can help you further. – zero point Feb 19 '16 at 22:38

1 Answers1

-1

Try this...

$(document).bind("#date-container", "click", function(){
    // do it to it...
});

That should bind the click event to even dynamically-created DOM.

m-albert
  • 1,089
  • 8
  • 15