Delete DOM element error

Using this code, I need to delete the generated new item. This does not work. JS errors do not appear in Firebug.

$('.popular-list li a').live("click",function() //this will apply to all anchor tags
            { 
                    var stuff = $(this).text();
                            var hasDuplicate = false;

          $('#favoritesdrinks li').each( function(){
           if ($(this).text() === stuff ){
              hasDuplicate = true;
              return false;
           }
        });

        if (hasDuplicate ) {
           alert("Already Added") } 
        else {         
           $('#favoritesdrinks').append('<li>'+stuff+' --- <a href="javascript:;" class="remove">Remove Item </a> </li>'); 
        }
    });

Removal:

  $("a.remove").click(function() {
    $(this).fadeOut(500, function() { $(this).remove(); });
    });
0
source share
2 answers

You need to use the .live event for anchors with class removal. Also the context of this will be an anchor inside the binding, so you need to use .parent () for fadeOut and remove li

$('.popular-list li a').live("click",function()  { 
   var stuff = $(this).text();
   var hasDuplicate = false;

   $('#favoritesdrinks li').each( function(){
      if ($(this).text() === stuff ){
          hasDuplicate = true;
          return false;
      }
   });

   if (hasDuplicate ) {
      alert("Already Added") } 
   else {         
      $('#favoritesdrinks').append('<li>'+stuff+' --- <a href="#" class="remove">Remove Item </a> </li>'); 
    }

  });

  $("a.remove").live('click', function(ev) {
    ev.preventDefault();
    $(this).parent().fadeOut(500, function(ev) { 
        $(this).remove(); 
    });
  });
+1
source
$("a.remove").click(function() { $(this).fadeOut(500, function() { $(this).remove(); }); });

This line will remove the A link, not the LI tag, because you are using $ (this)

0
source

Source: https://habr.com/ru/post/1714553/


All Articles