# 📚 JavaScript Tutorial - Part 4/10: DOM Manipulation & Events
#JavaScript #WebDev #FrontEnd #DOM
Welcome to Part 4 of our JavaScript series! Today we'll learn how to make web pages interactive by mastering DOM manipulation and event handling.
---
## 🔹 What is the DOM?
The Document Object Model is a tree-like representation of your webpage that JavaScript can interact with.
---
## 🔹 Selecting DOM Elements
### 1. Single Element Selectors
### 2. Multiple Element Selectors
---
## 🔹 Modifying the DOM
### 1. Changing Content
### 2. Styling Elements
### 3. Creating & Adding Elements
---
## 🔹 Event Handling
Responding to user interactions.
### 1. Inline Events (Avoid)
### 2. Recommended Approach
### 3. Common Event Types
| Event | Description |
|-------|-------------|
|
|
|
|
|
|
|
---
## 🔹 Event Object & Propagation
### 1. Event Object Properties
### 2. Stopping Propagation
### 3. Event Delegation
---
#JavaScript #WebDev #FrontEnd #DOM
Welcome to Part 4 of our JavaScript series! Today we'll learn how to make web pages interactive by mastering DOM manipulation and event handling.
---
## 🔹 What is the DOM?
The Document Object Model is a tree-like representation of your webpage that JavaScript can interact with.
<!-- HTML Structure -->
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id="main-title">Hello World</h1>
<ul class="items">
<li>Item 1</li>
<li>Item 2</li>
</ul>
</body>
</html>
graph TD
document --> html
html --> head
html --> body
head --> title
title --> text["My Page"]
body --> h1
h1 --> h1text["Hello World"]
body --> ul
ul --> li1["Item 1"]
ul --> li2["Item 2"]
---
## 🔹 Selecting DOM Elements
### 1. Single Element Selectors
// By ID (returns single element)
const title = document.getElementById('main-title');
// By CSS selector (first match)
const item = document.querySelector('.items li');
### 2. Multiple Element Selectors
// By class name (HTMLCollection)
const items = document.getElementsByClassName('item');
// By tag name (HTMLCollection)
const listItems = document.getElementsByTagName('li');
// By CSS selector (NodeList)
const allItems = document.querySelectorAll('.items li');
---
## 🔹 Modifying the DOM
### 1. Changing Content
// Text content (better for security)
title.textContent = 'New Title';
// HTML content (use carefully!)
title.innerHTML = '<em>New</em> Title';
// Attribute changes
title.setAttribute('class', 'highlight');
### 2. Styling Elements
// Direct style property access
title.style.color = 'blue';
title.style.fontSize = '2rem';
// Multiple styles at once
title.style.cssText = 'color: blue; font-size: 2rem;';
// Toggle classes
title.classList.add('highlight');
title.classList.remove('highlight');
title.classList.toggle('highlight');
### 3. Creating & Adding Elements
// Create new element
const newItem = document.createElement('li');
newItem.textContent = 'Item 3';
// Append to parent
const list = document.querySelector('ul');
list.appendChild(newItem);
// Insert at specific position
list.insertBefore(newItem, list.children[1]);
// Remove elements
list.removeChild(newItem);
---
## 🔹 Event Handling
Responding to user interactions.
### 1. Inline Events (Avoid)
<button onclick="handleClick()">Click Me</button>
### 2. Recommended Approach
const button = document.querySelector('button');
// Add event listener
button.addEventListener('click', function(e) {
console.log('Button clicked!', e.target);
});
// Remove event listener
button.removeEventListener('click', handleClick);### 3. Common Event Types
| Event | Description |
|-------|-------------|
|
click | Mouse click ||
dblclick | Double click ||
mouseenter/mouseleave | Hover effects ||
keydown/keyup | Keyboard input ||
submit | Form submission ||
load | Page/images loaded ||
scroll | Page scrolling |---
## 🔹 Event Object & Propagation
### 1. Event Object Properties
element.addEventListener('click', function(event) {
console.log(event.type); // "click"
console.log(event.target); // Clicked element
console.log(event.clientX); // Mouse X position
console.log(event.key); // Key pressed (for keyboard events)
});### 2. Stopping Propagation
// Stop bubbling up
event.stopPropagation();
// Prevent default behavior
event.preventDefault();
### 3. Event Delegation
document.querySelector('ul').addEventListener('click', function(e) {
if (e.target.tagName === 'LI') {
console.log('List item clicked:', e.target.textContent);
}
});---
❤2
## 🔹 Practical Example: Interactive Todo List
---
## 🔹 Working with Forms
### 1. Accessing Form Data
### 2. Form Validation
---
## 🔹 Best Practices
1. Cache DOM queries (store in variables)
2. Use event delegation for dynamic elements
3. Always prevent default on form submissions
4. Separate JS from HTML (avoid inline handlers)
5. Throttle rapid-fire events (resize, scroll)
---
### 📌 What's Next?
In Part 5, we'll cover:
➡️ Asynchronous JavaScript
➡️ Callbacks, Promises, Async/Await
➡️ Fetch API & AJAX
#JavaScript #FrontEnd #WebDevelopment 🚀
Practice Exercise:
1. Create a color picker that changes background color
2. Build a counter with + and - buttons
3. Make a dropdown menu that shows/hides on click
// DOM Elements
const form = document.querySelector('#todo-form');
const input = document.querySelector('#todo-input');
const list = document.querySelector('#todo-list');
// Add new todo
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value.trim() === '') return;
const todoText = input.value;
const li = document.createElement('li');
li.innerHTML = `
${todoText}
<button class="delete-btn">X</button>
`;
list.appendChild(li);
input.value = '';
});
// Delete todo (using delegation)
list.addEventListener('click', function(e) {
if (e.target.classList.contains('delete-btn')) {
e.target.parentElement.remove();
}
});
---
## 🔹 Working with Forms
### 1. Accessing Form Data
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
// Get form values
const username = form.elements['username'].value;
const password = form.elements['password'].value;
console.log({ username, password });
});### 2. Form Validation
function validateForm() {
const email = document.getElementById('email').value;
if (!email.includes('@')) {
alert('Please enter a valid email');
return false;
}
return true;
}---
## 🔹 Best Practices
1. Cache DOM queries (store in variables)
2. Use event delegation for dynamic elements
3. Always prevent default on form submissions
4. Separate JS from HTML (avoid inline handlers)
5. Throttle rapid-fire events (resize, scroll)
---
### 📌 What's Next?
In Part 5, we'll cover:
➡️ Asynchronous JavaScript
➡️ Callbacks, Promises, Async/Await
➡️ Fetch API & AJAX
#JavaScript #FrontEnd #WebDevelopment 🚀
Practice Exercise:
1. Create a color picker that changes background color
2. Build a counter with + and - buttons
3. Make a dropdown menu that shows/hides on click
❤2