How to Append an Element to another Element using JavaScript
Table of Contents
JavaScript offers powerful functionality for manipulating the DOM.
One of the most common operations to perform is appending an element to another element.
Because of the hierarchical nature of the DOM, when you want to insert a new element, you will need to find the parent and then append it as a child.
In this post, we're going to learn how to append an element to another element using JavaScript.
Appending an Element to Another Element
To start off, you'll first need to get the parent that you want to append the child to.
You can use querySelector()
to get the parent element:
JAVASCRIPTconst parent = document.querySelector(".parent");
Now you need to create the child element that you want to append to the parent.
To do this, you can use the createElement()
method from the document
object.
Then after that, feel free to add any attributes you want to the element, including the innerHTML
:
JAVASCRIPTconst child = document.createElement("div");
child.setAttribute("class", "child");
child.innerHTML = "Hello World!";
Once you have the parent and child, you can proceed to append the child to the parent:
JAVASCRIPTconst parent = document.querySelector(".parent");
const child = document.createElement("div");
child.setAttribute("class", "child");
child.innerHTML = "Hello World!";
parent.appendChild(child);
Keep in mind that you can only append elements to elements, and not strings or raw HTML.
Also, you can only append one element at a time. If you want to append multiple elements, you will need to make multiple calls to appendChild
.
Conclusion
In this post, we learned how to append an element to another element using JavaScript and the appendChild()
method.
The function is straightforward, you just need to get the parent and child elements to successfully use this method.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- How To Create a Modal Popup Box with CSS and JavaScript
- Getting Started with Moon.js