Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery remove div and previous label?

These are some input fields which i need to remove, but i am not able to remove the label tag

 <label class="prfx-row-title">Unique Selling Proposition </label>
 <div class="prfx-row-content">
     <input type="text" name="dynamic_usp[0][text]" placeholder="unique selling proposition " value="testing hello world" />
     <span class="remove button">Remove USP</span>
 </div>

$(".remove").live('click', function() {
            $(this).parent().remove();
            $(this).parent().prev('label.prfx-row-title').remove();
        });

Now only the div is remove but not the label?

Anyone?

like image 505
alex Avatar asked Sep 02 '26 04:09

alex


2 Answers

That's because when removing the div, it is no longer in the DOM, so the label is not a sibling anymore. remove the label first, then the div:

$(".remove").live('click', function() {
     $(this).parent().prev('label.prfx-row-title').remove();
     $(this).parent().remove();
});

Or better :

$(".remove").live('click', function() {
     $(this).parent().prev('label.prfx-row-title').remove()
     .end().remove();
});
like image 69
Karl-André Gagnon Avatar answered Sep 04 '26 20:09

Karl-André Gagnon


You can't remove prev() from something that is no longer there... so the easiest fix is just to rearrange the order...

$(".remove").live('click', function () {
    $(this).parent().prev('label.prfx-row-title').remove();
    $(this).parent().remove();
});

Also, if possible you might want to update the version of jquery you are using and use on() instead of live(). live() has been deprecated since 1.7 and removed since 1.9

JSFiddle


You could also consider changing your DOM to something like...

<div class="prfx-row">
    <label class="prfx-row-title">Unique Selling Proposition</label>
    <div class="prfx-row-content">
        <input type="text" name="dynamic_usp[0][text]" placeholder="unique selling proposition " value="testing hello world" /><span class="remove button">Remove USP</span>

    </div>
</div>

and that way you could just do..

$(this).closest("prfx-row").remove();

JSFiddle

like image 45
Dallas Avatar answered Sep 04 '26 20:09

Dallas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!