We can call appendChild
on a DOM node to append a child node to a given DOM node.
For instance, if we have the given div:
<div id='test'>
foo
</div>
Then we can append another div as a child of the div above with appendChild
.
To do this, we write:
const child = document.createElement('div');
child.innerHTML = 'bar';
const {
firstChild
} = child;
document.getElementById('test').appendChild(firstChild);
We call documenbt.createElement
to creat the child
div element.
Then we set its innerHTML
to the content we want inside the div.
Next, we get the firstChild
from child
.
And then we call appendChild
on the div with ID test
with firstChild
to append it as another child node of the div with ID test
.
Now we see ‘foo bar’ is displayed.
Append a String to the innerHTML Value
We can also just append a string to the innerHTML
directly.
So if we have:
<div id='test'>
foo
</div>
Then we can use the +=
operator to append a string into the div with ID test
by writing:
document.getElementById('test').innerHTML += ' bar'
And we get the same result as the previous example.