Nicest would be to wrap it in a reuseable custom function:
$.fn.swap = function(other) {
$(this).replaceWith($(other).after($(this).clone(true)));
};
So that you can use it as:
one.swap(other);
The clone(true)
is used so that events are also taken into account.
Here's an SSCCE which demonstrates swapping rows with its next row (if any):
<!doctype html>
<html lang="en">
<head>
<title>SO question 2078626 part I</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$.fn.swap = function(other) {
$(this).replaceWith($(other).after($(this).clone(true)));
};
$(document).ready(function() {
$('tr').css('cursor', 'pointer').click(function() {
$(this).swap($(this).next());
});
});
</script>
</head>
<body>
<table>
<tbody>
<tr><td>row1col1</td><td>row1col2</td><td>row1col3</td></tr>
<tr><td>row2col1</td><td>row2col2</td><td>row2col3</td></tr>
<tr><td>row3col1</td><td>row3col2</td><td>row3col3</td></tr>
<tr><td>row4col1</td><td>row4col2</td><td>row4col3</td></tr>
<tr><td>row5col1</td><td>row5col2</td><td>row5col3</td></tr>
</tbody>
</table>
</body>
</html>
Here's an SSCCE which demonstrates how it can be used in your particular case:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2078626 part II</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$.fn.swap = function(other) {
$(this).replaceWith($(other).after($(this).clone(true)));
};
$(document).ready(function() {
$('button.swap').click(function() {
$('#table tr:eq(1)').swap($('#table tr:eq(3)'));
});
});
</script>
</head>
<body>
<table id="table">
<tbody>
<tr><td>row1col1</td><td>row1col2</td><td>row1col3</td></tr>
<tr><td>row2col1</td><td>row2col2</td><td>row2col3</td></tr>
<tr><td>row3col1</td><td>row3col2</td><td>row3col3</td></tr>
<tr><td>row4col1</td><td>row4col2</td><td>row4col3</td></tr>
<tr><td>row5col1</td><td>row5col2</td><td>row5col3</td></tr>
</tbody>
</table>
<button class="swap">swap rows 2 and 4</button>
</body>
</html>
Note that the element index is zero based, hence the 1
and 3
in :eq()
.