0

My dynamic posts are added by .load() and they enter the DOM as such:

<div class="post">
    <h2>Basic Info</h2><button class="closer">X</button>
            <div class="innerPost">
               <h5>Notes:</h5>
                   <p>Lorem ipsum dolor sit amet.</p>
            </div>
 </div>

My jQuery to remove the the post works on the static first post on the page but not the newly added dynamic ones. Here is the jQuery:

     $(".closer").on('click', function() {
         $(this).parent().remove();
     });

I've been trying different selectors and reviewing similar problems from other people but still can't seem to get it work. Any help is much appreciated :)

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Holas
  • 29
  • 5

1 Answers1

3

This is because the elements are not in the DOM when the selector is run. Use event delegation.

$(document).on('click', ".closer", function() {
    $(this).parent().remove();
});
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • This works great.. i've only ever really use .click() , i'm tring to wrap my head around the .on() ... i think i understand now with the way you entered it i'm telling jQuery to start with the document and find the ".closer" where before it couldn't find anything as it wasn't there originally. Thanks so much! – Holas Jan 10 '15 at 00:34