jQuery removing an element and its sibling
Asked Answered
W

3

5

I have a table that has an even number of rows.

Odd rows are visible and have a delete button in them, even rows are hidden.

Delete should remove a pair, the odd row and the hidden even row.

The following only removes the odd row. How can I remove the odd row and the next sibling?

$('deleteButton').click(function() {
    var $tr = $(this).closest('tr');
    $tr.remove().next('tr').remove();
});

Many thanks

Wee answered 12/2, 2014 at 11:4 Comment(0)
W
10

You could use addBack() jQuery method:

$tr.next('tr').addBack().remove();
Wommera answered 12/2, 2014 at 11:8 Comment(2)
Thanks, It is very useful & addBack() is new for me :)Turbine
@A.Wolff: This is removing the current closest tr also. How can we preserve not removing the current row?Lind
U
1

Remove sibling first as removing the source row first will cause an error when trying to access the sibling of removed row.

$('deleteButton').click(function() {
    var $tr = $(this).closest('tr');
    $tr.next('tr').remove();
    $tr.remove();
});
Urson answered 12/2, 2014 at 11:6 Comment(0)
B
0

Use this,It will work,

$('deleteButton').click(function() {
    var $tr = $(this).closest('tr');
    $tr.next('tr').remove();
    $tr.remove();
});
Brickwork answered 12/2, 2014 at 11:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.