Skip to content
the poor coder

append div inside div js

Poor Man
Published
Reading time
1 min read
On this page

Append Div Inside Div in JavaScript#

If you want to add a div element inside another div element using JavaScript, you can use the DOM (Document Object Model) manipulation methods. This can be useful when you want to dynamically add new content to your webpage or modify existing content.

Using the appendChild Method#

One way to append a div element inside another div element is by using the appendChild() method.

Text

const parentDiv = document.querySelector('#parent-div');
const childDiv = document.createElement('div');
parentDiv.appendChild(childDiv);

In the code above, we first select the parent div element using the querySelector() method and store it in a variable called parentDiv. Then, we create a new div element using the createElement() method and store it in a variable called childDiv. Finally, we append the child div element to the parent div element using the appendChild() method.

Using the insertBefore Method#

Another way to append a div element inside another div element is by using the insertBefore() method.

Text

const parentDiv = document.querySelector('#parent-div');
const childDiv = document.createElement('div');
const siblingDiv = parentDiv.querySelector('.sibling-div');
parentDiv.insertBefore(childDiv, siblingDiv);

In the code above, we first select the parent div element using the querySelector() method and store it in a variable called parentDiv. Then, we create a new div element using the createElement() method and store it in a variable called childDiv. We also select a sibling div element using the querySelector() method and store it in a variable called siblingDiv. Finally, we insert the child div element before the sibling div element using the insertBefore() method.

Both the appendChild() and insertBefore() methods can be used to append any HTML element inside another HTML element using JavaScript.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC