Creating and Appending Elements
Use createElement, setAttribute, append, and remove to build and modify the DOM structure dynamically.
createElement
document.createElement(tagName) creates a new element in memory — it's not in the DOM yet. You then set its properties and append it to the tree.
const btn = document.createElement('button');
btn.textContent = 'Click Me';
btn.classList.add('btn-primary');
btn.setAttribute('type', 'button');
// btn is in memory, not yet in the pageappend and appendChild
parent.append(child) adds a node or string to the end of parent's children. appendChild is the older equivalent, but append is more flexible — it accepts multiple nodes and strings.
const list = document.querySelector('ul');
const item = document.createElement('li');
item.textContent = 'New item';
list.append(item); // adds to end of listAll lessons in this course
- querySelector and querySelectorAll
- addEventListener and Event Object
- Changing Content: textContent innerHTML classList
- Creating and Appending Elements