Skip to content Skip to sidebar Skip to footer

How To Remove An Element That Is Added Dynamically In Javascript

I have the following code to create some element:

Solution 1:

Because it's dynamic content, you can't bind events like the static content, it will not bind to the elements because they don't appear at the time you bind.

So you should bind event like this:

$('#parent').on('click', 'a.remove_block', function(events){
   $(this).parents('div').eq(1).remove();
});

Solution 2:

You need to use event delegation for dynamically added elements. Even though you have used .on() the syntax used does not use event delegation.

When you register a normal event it adds the handler to only those elements which exists in the dom at that point of time, but when uses event delegation the handler is registered to a element which exists at the time of execution and the passed selector is evaluated when the event is bubbled upto the element

$(document).on('click', '.remove_block', function(events){
   $(this).parents('div').eq(1).remove();
});

Solution 3:

$('a.remove_block').on('click',function(events){
  $(this).parents('.parent_div').remove();
  returnfalse;
});

Solution 4:

I had the situation where the dynamic element to remove wasn't a descendant of my event listener:

siteSel.on('select2:select', function (e) {
      // remove some other dynamic element on page.
});

Solution I found was using when() method.

siteSel.on('select2:select', function (e) {
      let dynamicElement = $('.element');
      $.when(dynamicElement).then(dynamicElement.remove());
});

Solution 5:

You can use the .live for this:

$('body').live('click','#idDinamicElement', function(){
   // your code here
});

Post a Comment for "How To Remove An Element That Is Added Dynamically In Javascript"