Basky
Basky

Reputation: 101

Swap table rows using javascript

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>

Upvotes: 1

Views: 3657

Answers (2)

user3235365
user3235365

Reputation: 21

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>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

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

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

Example fiddle

Upvotes: 4

Related Questions