.appendChild()
Published Mar 7, 2025
Contribute to Docs
The .appendChild()
method in JavaScript is a key DOM manipulation tool that appends a node (element or text node) as the last child of a specified parent. It allows developers to dynamically modify a webpage’s structure. If the node already exists in the DOM, it is moved to its new position. The method returns the appended node.
Syntax
parentNode.appendChild(childNode);
parentNode
: The parent element to which thechildNode
will be appended.childNode
: The node to append (element or text node).
Notes:
- If
childNode
already exists in the DOM, it is moved to the new position instead of being duplicated.- Unlike
.append()
,.appendChild()
accepts only a single node and does not support multiple nodes or strings.
Example
The following example shows how to use .appendChild()
to add a paragraph to a <div>
.
Here is the HTML code:
<div id="container"><p>This paragraph was added with appendChild!</p></div>
Here is the JavaScript code:
// Select the parent nodeconst parentDiv = document.getElementById('container');// Create a new paragraph elementconst newParagraph = document.createElement('p');// Add text content to the elementnewParagraph.textContent = 'This paragraph was added with .appendChild()!';// Append it as the last child to the parent nodeparentDiv.appendChild(newParagraph);
The output is of this code is as following:
This paragraph was added with .appendChild()!
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours