How do I remove the next elemen from $(this)?

I'm working with jQuery and found some issue. I have a button that will add a label and a span when clicked. But when I'm trying to remove the labels by clicking it one by one, the span with comma is not removed. I'd like to remove the span after the clicked label. Here's my script.

$('#btn_add_vendor').on('click', function(){
    var added = "<label class='label label-primary lbl_test'>MY LABEL</label><span class='add_comma'>,</span>";

    $('#div_label').append(added); //the label appended here, in a div.

    $('.lbl_test').click(function () {
       $(this).remove();
       $(this).next(".add_comma").remove(); //not working

    });
});

Answers 1

  • If you remove $(this)first, the reference to $(this) will not exist anymore. Try to change the order and do it like this:

    $('.lbl_test').click(function () {
       $(this).next(".add_comma").remove();
       $(this).remove();
    });
    

Related Articles