1

Here is the code which i think should insert the same rows again because we are using append() here. and not removing the rows first.

jQuery(document).ready(function(){
 jQuery('#add_rows').click(function(){
  
    var table = jQuery("#myTable");
    var rows = table.find('tr:gt(0)').toArray();
    for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})

});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<title>Sort a HTML Table Alphabetically</title>
</head>
<body>
<button id ="add_rows">Add rows </button>

<table id="myTable">
  <tr>
    <th class="sort_table">Name</th>
    <th class="sort_table">Country</th>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>North/South</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>Paris specialites</td>
    <td>France</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
  </tr>
</table>

If i use for (var i = 0; i < rows.length; i++){table.append('<tr><td>data1</td><td>data2</td></tr>')}

Then it actually add the rows (As i expected), but in first case it doesn't do the same, i think it has to do something with the fact that we are using objects there but i am not sure

Could someone explain the reason ?

thanks

2
  • It'll move the current rows you select. You might want to check the .clone() method in jQuery. Commented Dec 4, 2017 at 11:50
  • whch line exactly moving the current rows, could you pls explan ?@kmdm Commented Dec 4, 2017 at 11:51

1 Answer 1

4

Appending a child that already exists in the document moves it.

If you want to "clone" those rows, use table.find("tr:gt(0)").clone(); and append those.

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

1 Comment

Thanks, i didn't know that Appending a child that already exists in the document moves it. very informative, thanks

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.