Module 7: DOM Manipulation & Events

Master DOM manipulation, event handling, and modern web APIs for building interactive applications.

Back to Course|3.5 hours|Intermediate

DOM Manipulation & Events

Master DOM manipulation, event handling, and modern web APIs for building interactive applications.

Progress: 0/3 topics completed0%

Select Topics Overview

JavaScript DOM Introduction & Methods

Learn the Document Object Model (DOM), how to select elements, and fundamental DOM manipulation methods for creating dynamic web pages

Content by: Fiza Belim

Node.js Developer

Connect

DOM Fundamentals

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. JavaScript can manipulate the DOM to create dynamic and interactive web experiences.

DOM Structure

Code Example
// HTML Structure
<!DOCTYPE html>
<html>
<head>
    <title>DOM Example</title>
</head>
<body>
    <div id="container">
        <h1 id="title">Hello World</h1>
        <p class="text">This is a paragraph</p>
        <ul id="list">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
    </div>
</body>
</html>

// DOM Tree Structure
document
ā”œā”€ā”€ html
│   ā”œā”€ā”€ head
│   │   └── title
│   └── body
│       └── div#container
│           ā”œā”€ā”€ h1#title
│           ā”œā”€ā”€ p.text
│           └── ul#list
│               ā”œā”€ā”€ li
│               ā”œā”€ā”€ li
│               └── li
Swipe to see more code

Element Selection Methods

Code Example
// Element selection methods
// 1. getElementById - Select by ID
const title = document.getElementById('title');
console.log(title); // <h1 id="title">Hello World</h1>

// 2. getElementsByClassName - Select by class
const textElements = document.getElementsByClassName('text');
console.log(textElements); // HTMLCollection [p.text]

// 3. getElementsByTagName - Select by tag name
const paragraphs = document.getElementsByTagName('p');
console.log(paragraphs); // HTMLCollection [p.text]

// 4. querySelector - Select first matching element
const firstLi = document.querySelector('li');
const container = document.querySelector('#container');
const textClass = document.querySelector('.text');

// 5. querySelectorAll - Select all matching elements
const allLi = document.querySelectorAll('li');
const allText = document.querySelectorAll('.text');

console.log(allLi.length); // 3
console.log(allText.length); // 1

// 6. Modern selection methods
const container2 = document.querySelector('#container');
const title2 = container2.querySelector('#title'); // Search within container

// 7. Multiple selectors
const elements = document.querySelectorAll('h1, p, li');
console.log(elements.length); // 5 (1 h1 + 1 p + 3 li)

// 8. Attribute selectors
const elementsWithId = document.querySelectorAll('[id]');
const elementsWithClass = document.querySelectorAll('[class]');
const elementsWithData = document.querySelectorAll('[data-*]');
Swipe to see more code

DOM Manipulation Examples

Code Example
// DOM manipulation examples
// 1. Creating elements
const newDiv = document.createElement('div');
const newParagraph = document.createElement('p');
const newText = document.createTextNode('This is new text');

// 2. Setting content
newParagraph.textContent = 'This is a new paragraph';
newParagraph.innerHTML = '<strong>Bold text</strong> and <em>italic text</em>';

// 3. Setting attributes
newDiv.setAttribute('id', 'new-container');
newDiv.setAttribute('class', 'container new');
newDiv.id = 'new-container'; // Alternative way
newDiv.className = 'container new'; // Alternative way

// 4. Adding elements to DOM
const container = document.getElementById('container');
container.appendChild(newDiv);
container.appendChild(newParagraph);

// 5. Inserting elements
const referenceElement = document.querySelector('p');
container.insertBefore(newParagraph, referenceElement);

// 6. Removing elements
const elementToRemove = document.querySelector('.text');
container.removeChild(elementToRemove);

// 7. Replacing elements
const oldElement = document.querySelector('h1');
const newElement = document.createElement('h2');
newElement.textContent = 'New Title';
container.replaceChild(newElement, oldElement);

// 8. Cloning elements
const originalElement = document.querySelector('li');
const clonedElement = originalElement.cloneNode(true); // true = deep clone
container.appendChild(clonedElement);

// 9. Working with text content
const textElement = document.querySelector('p');
console.log(textElement.textContent); // "This is a paragraph"
console.log(textElement.innerText); // "This is a paragraph"
console.log(textElement.innerHTML); // "This is a paragraph"

// 10. Style manipulation
const styledElement = document.querySelector('h1');
styledElement.style.color = 'red';
styledElement.style.backgroundColor = 'yellow';
styledElement.style.fontSize = '24px';
styledElement.style.margin = '10px 0';

// 11. Class manipulation
const classElement = document.querySelector('div');
classElement.classList.add('highlighted');
classElement.classList.remove('old-class');
classElement.classList.toggle('active');
console.log(classElement.classList.contains('highlighted')); // true
Swipe to see more code

Practice Exercise: DOM Basics

Code Example
// Exercise: Build a Dynamic Todo List
// HTML structure needed:
/*
<div id="todo-app">
    <h1>Todo List</h1>
    <div id="todo-input">
        <input type="text" id="new-todo" placeholder="Add new todo...">
        <button id="add-todo">Add</button>
    </div>
    <ul id="todo-list"></ul>
</div>
*/

class TodoApp {
    constructor() {
        this.todos = [];
        this.todoInput = document.getElementById('new-todo');
        this.addButton = document.getElementById('add-todo');
        this.todoList = document.getElementById('todo-list');
        
        this.initializeEventListeners();
    }
    
    initializeEventListeners() {
        this.addButton.addEventListener('click', () => this.addTodo());
        this.todoInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.addTodo();
            }
        });
    }
    
    addTodo() {
        const text = this.todoInput.value.trim();
        if (text) {
            const todo = {
                id: Date.now(),
                text: text,
                completed: false
            };
            
            this.todos.push(todo);
            this.renderTodo(todo);
            this.todoInput.value = '';
        }
    }
    
    renderTodo(todo) {
        const li = document.createElement('li');
        li.id = `todo-${todo.id}`;
        li.className = 'todo-item';
        
        li.innerHTML = `
            <input type="checkbox" ${todo.completed ? 'checked' : ''}>
            <span class="todo-text">${todo.text}</span>
            <button class="delete-btn">Delete</button>
        `;
        
        // Add event listeners
        const checkbox = li.querySelector('input[type="checkbox"]');
        const deleteBtn = li.querySelector('.delete-btn');
        const textSpan = li.querySelector('.todo-text');
        
        checkbox.addEventListener('change', () => this.toggleTodo(todo.id));
        deleteBtn.addEventListener('click', () => this.deleteTodo(todo.id));
        
        this.todoList.appendChild(li);
    }
    
    toggleTodo(id) {
        const todo = this.todos.find(t => t.id === id);
        if (todo) {
            todo.completed = !todo.completed;
            const li = document.getElementById(`todo-${id}`);
            const textSpan = li.querySelector('.todo-text');
            
            if (todo.completed) {
                textSpan.style.textDecoration = 'line-through';
                textSpan.style.color = '#888';
            } else {
                textSpan.style.textDecoration = 'none';
                textSpan.style.color = '#000';
            }
        }
    }
    
    deleteTodo(id) {
        this.todos = this.todos.filter(t => t.id !== id);
        const li = document.getElementById(`todo-${id}`);
        if (li) {
            li.remove();
        }
    }
}

// Initialize the app
// const todoApp = new TodoApp();
Swipe to see more code

šŸŽÆ Practice Exercise

Test your understanding of this topic:

Ready for the Next Module?

Continue your learning journey and master the next set of concepts.

Continue to Module 8