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
Views:
391
No Comments on Append and AppendChild in JavaScript