Understanding the DOMLesson 1.5
Creating and inserting DOM elements dynamically with JavaScript
createElement, appendChild, append, prepend, insertAdjacentElement, removeChild, remove, cloneNode, DocumentFragment
Creating and Inserting Elements
To add content dynamically, you create a node, configure it, then insert it into the tree.
Create, Configure, Insert
const li = document.createElement('li');
li.textContent = 'New item';
li.classList.add('task');
const list = document.querySelector('ul');
list.appendChild(li); // adds at end
list.prepend(li); // adds at startinsertAdjacentElement
For precise positioning relative to an existing element, use insertAdjacentElement. Its first argument is one of four position strings: beforebegin, afterbegin, beforeend, afterend.
const ref = document.querySelector('.ref-item');
const newEl = document.createElement('p');
newEl.textContent = 'Inserted after';
ref.insertAdjacentElement('afterend', newEl);Removing Elements
const old = document.querySelector('.outdated');
old.remove(); // modern, directDocumentFragment for Batching
When inserting many nodes at once, use a DocumentFragment to avoid multiple reflows.
const frag = document.createDocumentFragment();
['A','B','C'].forEach(text => {
const li = document.createElement('li');
li.textContent = text;
frag.appendChild(li);
});
document.querySelector('ul').appendChild(frag);