1

Am trying to do like this,

<table>
    <tr id="ID1"><td></td></tr>
    <tr id="ID2"><td></td></tr>
</table>

I need to swap table rows index position like as follows

<table>
    <tr id="ID2"><td></td></tr>
    <tr id="ID1"><td></td></tr>
</table>

I tried to fix it using jQuery as:

$('#ID1').after('#ID2');

Can anyone help me to fix the above requirement using javascript?

$('#ID1').after('#ID2');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr id="ID1">
    <td></td>
  </tr>
  <tr id="ID2">
    <td></td>
  </tr>
</table>

2 Answers 2

4

after() is used to insert content. To move or add elements, use insertAfter():

$('#ID1').insertAfter('#ID2');

Example fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

after can move things, but it doesn't if you give it a string. $('#ID2').after($('#ID1')); works, for instance: jsfiddle.net/sbkL785c/1
@T.J.Crowder Good point. inserAfter is cleaner though as it just takes the selector.
Yes. (And in general, insertAfter tends to be clearer to me anyway.) I was quite surprised by the OP's after behavior, though -- the docs suggest the two are just converses of each other, when clearly that's not quite the case.
0

Swap row by appendChild.

var x = document.getElementById("first");
var table = document.getElementById("table");
table.appendChild(x);
 <table id="table">
    <tr id="first"><td>First</td></tr>
    <tr id="second"><td>Second</td></tr>
 </table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.