You want to use appendChild or insertBefore as little as possible because it’s an expensive process to add elements to the DOM—everything after the element you added needs to be repainted by the browser.
const devs = ['Addy Osmani', 'Vitaly Friedman', 'Chris Coyier']
// Don't do this! It causes the DOM to update three times
const ol = document.querySelector('ol')
devs.forEach(dev => {
const li = document.createElement('li')
li.innerHTML = dev
ol.appendChild(li)
})
There are two better ways to add multiple elements to the DOM.
Replacing innerHTML
Appending a document fragment
Replacing innerHTML
You can change multiple elements at once by changing the element’s innerHTML.
For example, let’s say you want to add three developers to an empty list.
The downside of this approach? You replace the entire list. The GIF below proves that the first three items are also replaced even though they’re not changed.
A better approach to add multiple items is through a document fragment.
Using a document fragment
A document fragment is like a separate DOM that lives only in JavaScript. It functions exactly like the DOM.
To create a document fragment, you use createDocumentFragment.
const fragment = document.createDocumentFragment()
Document fragments can be treated like the DOM. That means you can add elements to the fragment with appendChild and insertBefore. Any changes you make to the fragment will not be reflected in the DOM (and hence not expensive) until you add the fragment into the DOM.
// DOM doesn't change with this code
devs.forEach(dev => {
const li = document.createElement('li')
li.innerHTML = dev
fragment.appendChild(li)
})
You can add the fragment to the DOM with appendChild or insertBefore when you’re ready.
ol.appendChild(fragment)
In this case, you can see from the GIF that the first three elements remain. You only added three more items into the list.
Add a list of humans to .characters. This list should have a humans class and contains five list items—Gandalf, Saruman, Aragorn, Boromir, and Faramir.
Add two list items—Glorfindel and Elrond—before Arwen Evenstar. Use the document fragment method.
Answers
Add a list of humans to .characters. This list should have a humans class and contains five list items—Gandalf, Saruman, Aragorn, Boromir, and Faramir.