1

I know that append() is a method that inserts a list of node objects as the last child of the element it is called on. My question is, why in the following code the .append() method doesn't add additional elements as its last children instead, it acts as if it modified the original elements.

let tbody = grid.querySelector('tbody');
let rowsArray = Array.from(tbody.rows);
tbody.append(...rowsArray);
<html>

<head>
  <meta charset="utf-8" />
</head>

<body>
  <table id="grid">
    <thead>
      <tr>
        <th data-type="number">Age</th>
        <th data-type="string">Name</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>5</td>
        <td>John</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Pete</td>
      </tr>
      <tr>
        <td>12</td>
        <td>Ann</td>
      </tr>
      <tr>
        <td>9</td>
        <td>Eugene</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Ilya</td>
      </tr>
    </tbody>
  </table>
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • 1
    An element can only exist in one place in the DOM. You're appending the elements, but not cloning them, so it 'moves' the elements to the end of the parent. If you were to clone them you would see them duplicated `Array.from(tbody.rows).map(row => row.cloneNode(true));` – pilchard Jul 15 '22 at 09:45

1 Answers1

1

An element can only exist in one place in the DOM. You're appending the elements, but not cloning them, so it has the effect of moving those elements to the end of the parent. If you were to clone them you would see them duplicated, here using cloneNode().

let tbody = grid.querySelector('tbody');
let rowsArray = Array.from(tbody.rows).map(row => row.cloneNode(true));
tbody.append(...rowsArray);
<table id="grid"> <thead> <tr> <th data-type="number">Age</th> <th data-type="string">Name</th> </tr> </thead> <tbody> <tr> <td>5</td> <td>John</td> </tr> <tr> <td>2</td> <td>Pete</td> </tr> <tr> <td>12</td> <td>Ann</td> </tr> <tr> <td>9</td> <td>Eugene</td> </tr> <tr> <td>1</td> <td>Ilya</td> </tr> </tbody></table>
pilchard
  • 12,414
  • 5
  • 11
  • 23