0

When you start an HTML page you start with a certain set of elements. The user can then obviously add new elements to the page and those changes can immediately be viewed. One problem I have noticed though is that javascript/jquery isn't able to see these newly added elements, it is as though it can only see the elements that were present when the page was loaded (so the elements in the HTML page). Therefore you can't add any events to those new elements.

$('#old_element').on('click', function() {
 var frag = $('<div class='new_element'></div>')
 $('#old_element').append(frag);
})

$('.new_element').on('click', function() {
$(this).hide();
})

Here you can see an example I made.

I couldn't find any place that had an answer for this, so does anyone here have any?

Ad Dan
  • 1
  • duplicate link will help. Also read [Understanding Event Delegation](https://learn.jquery.com/events/event-delegation/) – charlietfl Apr 07 '18 at 22:00
  • Sorry they didn't take time to understand the actual problem here... You'll see that the event gets added to the new element, but you put the new element inside the old element, so when new element is clicked, the old one is too, creating a new new element! See fiddle: https://jsfiddle.net/yghzshLw/ – Timothy Kanski Apr 07 '18 at 22:19

0 Answers0