In today's post, I'll be taking you through 2 of my favourite ways to append multiple child elements to a parent element with the JavaScript DOM.
1. insertAdjacentHTML()
This is one of the most underrated methods in JavaScript. You can use insertAdjacentHTML()
to insert an HTML string at a specified position relative to a parent element.
It supports a total of 4 positions, but the one we're interested in for appending elements is beforeend
(insert before the end of the parent element).
Let's see it in action.
/*
HTML:
<ul id="fruit">
<li>Apple</li>
<li>Banana</li>
</ul>
*/
const fruitList = document.getElementById("fruit");
// Add 3 new <li>'s to the list of fruits
fruitList.insertAdjacentHTML("beforeend", `
<li>Pear</li>
<li>Orange</li>
<li>Grape</li>
`);
As you can see, it's easy to append multiple elements using plain HTML. To make it even simpler, you can use template literals to take advantage of multi-line HTML as I've done above ๐
2. append()
The above technique uses HTML strings, but what if you wanted to build the DOM elements manually? Sometimes, doing it this way makes it easy to add event listeners or perform operations on the elements.
Let's explore the same example as above, this time using the append()
method which works like appendChild()
but lets you pass in multiple items.
/*
HTML:
<ul id="fruit">
<li>Apple</li>
<li>Banana</li>
</ul>
*/
const fruitList = document.getElementById("fruit");
const pearListItem = document.createElement("li");
const orangeListItem = document.createElement("li");
const grapeListItem = document.createElement("li");
pearListItem.textContent = "Pear";
orangeListItem.textContent = "Orange";
grapeListItem.textContent = "Grape";
// Add 3 new <li>'s to the list of fruits
fruitList.append(pearListItem, orangeListItem, grapeListItem);
It's also worth noting that the append()
method also lets you pass in text nodes or plain-text strings.
If you have any other techniques, please leave them down below!
Enrol Now ๐ JavaScript DOM Crash Course
You can find a complete course on the JavaScript DOM which goes over some of the topics covered in this post at the link below ๐
Happy coding ๐
Top comments (2)
Hy Dom,
Nice thank you.
I have assembled some functions in my MVU library, which precisely aims at creating and appending elements easily.
You can test it here : DemoDom
Nice