Steven
Steven

Reputation: 167

Selecting newly added elements with jquery

I'm currently adding new buttons using append() function.

Since these new buttons were not present on page load, they are not selectable.

I found one way to make it work by placing the code inside of

$(document).on("mouseover", ".container", function() { ...

but it's not reliable. I can't believe it's the only way around, surely there must be something more suitable, right?

$('.button').on('click', function() {
  $('.container').append('<br /><button class="addedbutton">Added button</button>');
})

$('.addedbutton').on('click', function() {
  $(this).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <button class="button">Add a button</button>
</div>

Upvotes: 1

Views: 59

Answers (1)

Mamun
Mamun

Reputation: 68933

Try using delegation approach which will ensure that events will be attached to the elements that are added to the document at a later time:

$('.container').on('click', '.addedbutton', function() {

$('.button').on('click', function() {
  $('.container').append('<br /><button class="addedbutton">Added button</button>');
});

$('.container').on('click', '.addedbutton', function() {
  $(this).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <button class="button">Add a button</button>
</div>

Upvotes: 3

Related Questions