Implemented dynamic addition of <li> list items with nested <a><i></i></a> elements. The task is to remove the parent element <li> by clicking on the embedded <i> element, which in turn is nested in <a> .

Markup:

 <div id="tabsSlide" class="tabs-slider"> <ul class="tabs-slider-wrapper nav nav-tabs js_order_service_tabs"> <li class="js_order_request_service_tab"> <a href="#order_service" data-toggle="tab"> <i class="icon icon-remove js_remove_service_tab"></i>Tab </a> </li> </ul> </div> 

Item delete code:

 $('#removeTab').click(function(){ $(this).parent().remove(); }); 

Full code

Now when you click on the delete icon in the <i> , all dynamically created <li> elements are deleted. And you only need to remove the parent <li> element with all its contents.

    2 answers 2

    Try this:

     $('body').on('click', '.js_remove_service_tab', function(e) { $(this).closest('.js_order_request_service_tab').remove(); }); 

    A click is hung through the body, because the elements are added dynamically.

    • one
      closest better than parents , because it will stop as soon as it finds the item. - Qwertiy
    • @Qwertiy, thanks. Corrected the answer. - Andrei Katalkin

    you have removeTab this Id, it must be unique on the page

    v.1

    According to the idea it should be so, but the event should be hung on each added node:

     $('#tabsSlide i.icon-remove').unbind().click(function(){ $(this).parents('li').remove(); }); 

    v.2

    but it is better to correct the layout of the deleted element:

     $('#TabAdded').click(function () { $('#TabAdded').before('<li class="js_order_request_service_tab"><a href=""><i id="removeTab" class="icon icon-remove js_remove_service_tab" onclick="del(this)"></i>Tab</a></li>'); }); 

    ...

     function del(t) { $(t).closest('.js_order_request_service_tab').remove(); } 

    in this variant, the reference to the element being deleted is relative

    • what is this .unbind() such) Why is he here - Vasily Barbashev
    • Well, probably because the click added not to one (new) element, but to all those found - ravend
    • this is not the answer to the question of why unbind needed unbind :) - Vasily Barbashev
    • unbind to delete the previous event'ов , otherwise in the list of 100 positions on the first node will hang on 100 events, on the second one 99, etc. Although it is better to alter the layout so that the link is relative: <i id="removeTab" class="icon icon-remove js_remove_service_tab" onclick="del(this)"></i> function del(t){$(t).closest('.js_order_request_service_tab').remove();} - ravend
    • add to your answer your suggestion, tell the person how to do it correctly. - Vasily Barbashev