Member-only story
Two methods making DOM manipulation less verbose.
append()
is a convenient alternative to appendChild()
.
Like appendChild()
, append()
appends DOM nodes to an element, but unlike appendChild()
, append()
accepts multiple arguments of any types. The arguments that are not nodes are converted into strings that in turn are converted into text nodes. Then, the mixture of elements and text nodes is appended to the parent node using the same mechanism as in appendChild()
.
For example, let’s call append()
of an empty div
with several arguments of different types — a date, an array and a div
element:
const div = document.createElement('div');
div.appendChild(document.createTextNode('TEST'));
div.style.color = 'red';
root.append(new Date(), [1, 2, 3], div);
The append()
inserts two text nodes and one element into the parent div
whose id
is root
:
The created nodes are displayed in the browser:
Note that, in the script, the second line adding the text to the created div
:
div.appendChild(document.createTextNode('TEST'));
can be simplified using append()
:
div.append('TEST');