Append and appendChild are two common methods used to add elements to the document Object Model (DOM). They are often used interchangeably without too much hassle, but if they are the same, then why have two apis? … They are similar, but not the same.

.append()

This method is used to add elements in the form of a Node object or a DOMString, which is basically text.

Insert a Node object

const parent = document.createElement('div');
const child = document.createElement('p');
parent.append(child);
// This appends the child element to the div element

      

Copy the code

This appends the child element to the div element, and the div looks something like this

<div> <p> </ p> </ div>
Copy the code

Insert the DOMString

const parent = document.createElement('div');
parent.append('Additional text');
Copy the code

And then div looks something like this

<div>Additional text</ div>
Copy the code

.appendChild()

Similar to the.append method, this method is used for elements in the DOM, but in this case, only a Node object is accepted.

Insert a Node object

const parent = document.createElement('div');
const child = document.createElement('p');
parent.appendChild(child);
Copy the code

This appends the child element to the div element, and the div looks something like this

<div> <p> </ p> </ div>
Copy the code

Insert the DOMString

const parent = document.createElement('div');
parent.appendChild('Appending Text');
// Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'
Copy the code

The difference between

Append accepts Node objects and DOMString, while. AppendChild accepts only Node objects.

const parent = document.createElement('div');
const child = document.createElement('p');
// Appends node objects
parent.append(child) // It works fine
parent.appendChild(child) // It works fine
/ / append DOMStrings
parent.append('Hello world') // It works fine
parent.appendChild('Hello world') // Throw an error
Copy the code

.append returns no value, while.appendChild returns the attached Node object.

const parent = document.createElement('div');
const child = document.createElement('p');
const appendValue = parent.append(child);
console.log(appendValue) // undefined
const appendChildValue = parent.appendChild(child);
console.log(appendChildValue) // <p><p>
Copy the code

.append allows you to add multiple projects, while.appendChild allows only a single project.

const parent = document.createElement('div');
const child = document.createElement('p');
const childTwo = document.createElement('p');
parent.append(child, childTwo, 'Hello world'); // It works fine
parent.appendChild(child, childTwo, 'Hello world');
// Works fine, but adds the first element and ignores the rest
Copy the code

conclusion

You can use.append when you can use.appendChild, but not the other way around.


Source: Dev.to, written by Abdulqudus Abubakre, translated by Public account: Front-end Full Stack Developer