alex
alex

Reputation: 4924

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?

Upvotes: 3

Views: 5924

Answers (2)

Smern
Smern

Reputation: 19086

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

Upvotes: 4

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33880

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();
});

Upvotes: 6

Related Questions