Jquery remove div and previous label?
These are some input fields that I need to remove, but I cannot 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 removed but not the label?
Anyone?
source to share
This is because when deleted, div
it is no longer in the DOM, so the shortcut is no longer a sibling. first remove the label, then 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();
});
source to share
You cannot remove prev()
from what no longer exists ... so the simplest fix is to just reorder ...
$(".remove").live('click', function () {
$(this).parent().prev('label.prfx-row-title').remove();
$(this).parent().remove();
});
Also, if possible, you may need to update the version of jquery you are using and use on()
instead live()
. live()
deprecated as of 1.7 and retired as of 1.9
You might also consider changing the 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();
source to share