Satellite Sage
Satellite Sage

Reputation: 470

Why does .append() replaces the content of the tbody in the code below?

I have this simple html file that just contains a table.

<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Duration</th>
            <th>Date</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Animals</td>
            <td>6:40</td>
            <td>2005-12-21</td>
        </tr>
        <tr>
            <td>Deer</td>
            <td>6:24</td>
            <td>2014-02-28</td>
        </tr>
        <tr>
            <td>Ghost</td>
            <td>11:40</td>
            <td>2012-04-10</td>
        </tr>
        <tr>
            <td>Wagons</td>
            <td>21:40</td>
            <td>2007-04-12</td>
        </tr>
    </tbody>
</table>

And then, my JavaScript is as follows.

$(function() {
    var $tbody = $("tbody");
    var rows = $tbody.find("tr").toArray();
    $tbody.append(rows.reverse());
});

The output was like this:

+---------+----------+------------+
| Title   | Duration | Date       |
+---------+----------+------------+
| Wagons  | 21:40    | 2007-04-12 |
| Ghost   | 11:40    | 2012-04-10 |
| Deer    | 6:24     | 2014-02-28 |
| Animals | 6:40     | 2005-12-21 |
+---------+----------+------------+

However, the table below is what I was expecting.

+---------+----------+------------+
| Title   | Duration | Date       |
+---------+----------+------------+
| Animals | 6:40     | 2005-12-21 |
| Deer    | 6:24     | 2014-02-28 |
| Ghost   | 11:40    | 2012-04-10 |
| Wagons  | 21:40    | 2007-04-12 |
| Wagons  | 21:40    | 2007-04-12 |
| Ghost   | 11:40    | 2012-04-10 |
| Deer    | 6:24     | 2014-02-28 |
| Animals | 6:40     | 2005-12-21 |
+---------+----------+------------+

Can someone please explain why was the content of tbody replaced instead of just having more rows?

Upvotes: 1

Views: 71

Answers (1)

charlietfl
charlietfl

Reputation: 171669

Use clone() to make copies if that is what you are wanting to do .

When you append an element it can only exist once and append does not make a copy of it

$(function() {
    var $tbody = $("tbody");
    var rows = $tbody.find("tr").clone().toArray();
    $tbody.append(rows.reverse());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Duration</th>
            <th>Date</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Animals</td>
            <td>6:40</td>
            <td>2005-12-21</td>
        </tr>
        <tr>
            <td>Deer</td>
            <td>6:24</td>
            <td>2014-02-28</td>
        </tr>
        <tr>
            <td>Ghost</td>
            <td>11:40</td>
            <td>2012-04-10</td>
        </tr>
        <tr>
            <td>Wagons</td>
            <td>21:40</td>
            <td>2007-04-12</td>
        </tr>
    </tbody>
</table>

Upvotes: 3

Related Questions