amklogo

Append and AppendChild in JavaScript

Home » Append and AppendChild in JavaScript

Append and AppendChild in JavaScript

The append and appendchild Methods are too popular and used to add elements into the Document Object Model(DOM).

But there is a main difference between them, if you don’t get the hang of it, it may cause some errors in your project, so let’s see what is the difference between them when to use append or appendChild in your project.

Element.append()

The Element.append() method inserts a set of Node objects or DOMString objects after the last child of the Element.

Syntax:

append(nodesOrDOMStrings)

Example:

// Inserting a DOMString (text)
const parent = document.createElement('div');

parent.append('Appending Text');

// The div would then look like this <div>Appending Text</div>

Node.appendChild()

The Node.appendChild() method adds a Node and only NODE, to the end of the list of children of a specified parent node.

Syntax:

element.appendChild(a child)

Example:

// Inserting a Node object
const parent = document.createElement('div');
const child = document.createElement('p');

parent.appendChild(child);

// This appends the child element to the div element
// The div would then look like this <div><p></p></div>
// Inserting a 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'

Differences:

Element.append()Node.appendChild()
accepts Node objects and DOMStrings.accepts only Node objects.
does not have a return value.returns the appended Node object.
allows you to add multiple items.allows only a single item

you can find more useful articles on AMK

Share:

I’m Front End Developer with more than 2 years of experience, I love to learn every day, and share this knowledge with other developers. if you are reading this now, I wish you have a great day!

No Comments on Append and AppendChild in JavaScript

Related Posts:

best-css-frameworks
CSS

Best CSS Frameworks in 2021

1. Bootstrap 2. Foundation 3. Bulma 4. Tailwind CSS 5. UI Kit 6. Milligram 7. Materialize CSS Bootstrap Quickly design and customize responsive mobile-first sites

music-player
JavaScript

Music Player With Vanilla JavaScript

In this blog tutorial, we are going to set up and build a music player with vanilla JavaScript from scratch ‘without audio tag’, you can

functionVsMethod
JavaScript

JavaScript Difference between Methods and Functions

JavaScript Functions: A function is a block of code written to perform some specific set of tasks. We can define a function using the function keyword, followed by Name and