Learn how to add one or more HTML elements using appendChild() method in JavaScript.
- appendChild() → you’re here
- append()
- append() vs appendChild()
1. Add Element Using appendChild()
Here is a simple HTML Markup
<section id="box-wrapper">
<div class="box">div <br>1</div>
<div class="box">div <br>2</div>
<div class="box">div <br>3</div>
<div class="box">div <br>4</div>
</section>
When you call the appendChild() method, it will add the newly created elements after the last child of the element inside the parent element.
Which is similar to the append() method.
But there are a few key differences between append() and appendChild() method.
const boxWrapper = document.getElementById("box-wrapper");
const box = document.createElement("div");
box.innerHTML = 'div <br> 5';
box.style.backgroundColor = "orange";
box.classList.add("box");
boxWrapper.appendChild(box);
2. Add Multiple Child Elements As Siblings
Unlike the append() method, the appendChild() only allows you to add a single element in a single query.
If you want to add more child elements for the same parent, you’ll need to call it again with a new element as an argument.
const boxWrapper = document.getElementById("box-wrapper");
const box5 = document.createElement("div");
box5.innerHTML = 'div <br> 5';
box5.style.backgroundColor = "orange";
box5.classList.add("box");
const box6 = document.createElement("div");
box6.innerHTML = 'div <br> 6';
box6.style.backgroundColor = "orange";
box6.classList.add("box");
boxWrapper.appendChild(box5);
boxWrapper.appendChild(box6);
3. Add Nested Child Elements One Inside The Other
Using appendChild(), we can easily add one element inside another element by chaining the appendChild() methods.
Unlike the append() method, the appendChild() method returns the appended element.
As you can see, I’ve called the appendChild() method on the boxWrapper object.
The argument is Object.assign() which is one of the easiest way to chain appendChild() to add nested child elements.
It takes two arguments.
- **Element **that you want to create, like div or buttons
- A JavaScript object where you’ll add one or more properties for the element.
boxWrapper.appendChild(
Object.assign(
document.createElement('div'),
{ classList : 'box',
innerHTML: "div <br>5"
}
)
).appendChild(
Object.assign(
document.createElement("button"), {
innerHTML: "Button"
}
)
)
In here, I first added the div elements which is box 5.
Then, I’ve chained the appendChild() method to add a child element inside the box 5 element which is the button.
Top comments (0)