appendChild method

The appendChild method allows you to insert some other element at the end. Most commonly it used after creating an element with createElement.

Syntax

javascriptparent.appendChild(element);

Example

Let's create a paragraph, set its text and place it on a page at the end of the #parent block:

html<div id="parent">
  <p>1</p>
  <p>2</p>
  <p>3</p>
</div>
javascriptlet parent = document.querySelector('#parent');

let p = document.createElement('p');
p.textContent = '!';

parent.appendChild(p);

The code execution result:

html<div id="parent">
  <p>1</p>
  <p>2</p>
  <p>3</p>
  <p>!</p>
</div>

Example

ul is given. Let's place 9 li tags in it, while setting serial numbers as their text:

html<ul id="parent"></ul>
javascriptlet parent = document.querySelector('#parent');

for (let i = 1; i <= 9; i++) {
  let li = document.createElement('li');
  li.textContent = i;
  parent.appendChild(li);
}

The code execution result:

html<ul id="parent">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
</ul>

Example

Let's populate a table with tr's and td's:

html<table id="table"></table>
javascriptlet parent = document.querySelector('#parent');

for (let i = 1; i <= 3; i++) {
  let tr = document.createElement('tr'); // we create a tr
  
  // We populate tr with td's:
  for (let j = 1; j <= 3; j++) {
    let td = document.createElement('td'); // we create a td
    td.textContent = j; // write a text in it
    
    tr.appendChild(td); // add the created td to the end of the tr
  }
  
  table.appendChild(tr); // add the created tr to the end of the table
}

The code execution result:

html<table id="table">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
</table>

See also