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
parent.appendChild(element);
Example
Let's create a paragraph, set its text
and place it on a page at the end of
the #parent
block:
<div id="parent">
<p>1</p>
<p>2</p>
<p>3</p>
</div>
let parent = document.querySelector('#parent');
let p = document.createElement('p');
p.textContent = '!';
parent.appendChild(p);
The code execution result:
<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:
<ul id="parent"></ul>
let 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:
<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:
<table id="table"></table>
let 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:
<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
-
the
append
method
that inserts elements at the end -
the
insertBefore
method
that inserts an element before an element -
the
insertAdjacentElement
method
that inserts an element at the given location -
the
insertAdjacentHTML
,
that inserts tags at the given location