DOM Manipulation and EventsLesson 5.3
Dynamic DOM Manipulation
createElement, appendChild, insertBefore, removeChild, cloneNode, template literals for DOM, reading form values
Dynamic DOM Manipulation
Beyond reading and modifying existing elements, JavaScript lets you create new elements and insert them into the DOM, or remove elements entirely. This is how modern web applications update the page without full reloads.
Creating Elements
const newParagraph = document.createElement('p');
newParagraph.textContent = 'This paragraph was created by JavaScript.';
newParagraph.classList.add('info-text');
const container = document.querySelector('#app');
container.appendChild(newParagraph);Inserting in Specific Positions
const list = document.querySelector('ul');
const newItem = document.createElement('li');
newItem.textContent = 'New item';
// Insert before the first item
const firstItem = list.firstElementChild;
list.insertBefore(newItem, firstItem);
// Modern approach with insertAdjacentElement
firstItem.insertAdjacentElement('beforebegin', newItem);Removing Elements
const itemToRemove = document.querySelector('.outdated');
itemToRemove.remove(); // Modern, clean
// Or with parent reference
const parent = document.querySelector('#list');
const child = parent.querySelector('.item');
parent.removeChild(child);Building Lists from Data
const tasks = [
{ id: 1, text: 'Buy groceries', done: false },
{ id: 2, text: 'Write report', done: true },
{ id: 3, text: 'Call doctor', done: false }
];
const list = document.querySelector('#task-list');
tasks.forEach(task => {
const li = document.createElement('li');
li.innerHTML = `
<span class="${task.done ? 'done' : ''}">${task.text}</span>
<button data-id="${task.id}">Delete</button>
`;
list.appendChild(li);
});Reading Form Values
const form = document.querySelector('#signup-form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const name = form.querySelector('#name').value.trim();
const email = form.querySelector('#email').value.trim();
if (!name || !email) {
alert('Please fill in all fields.');
return;
}
console.log({ name, email });
});