The Document Object Model (DOM)
The DOM is a programming interface for HTML and XML documents. It represents the structure of a document as a tree-like hierarchy, allowing JavaScript to dynamically access and manipulate the content, structure, and style of a web page.
Selecting DOM Elements
JavaScript provides several methods to select elements from the DOM:
- By ID:
let element = document.getElementById('myId');
- By Class Name:
let elements = document.getElementsByClassName('myClass');
- By Tag Name:
let elements = document.getElementsByTagName('div');
- Using CSS Selectors:
let element = document.querySelector('.myClass');
let elements = document.querySelectorAll('p');
Modifying DOM Elements
Once you’ve selected an element, you can modify its content, attributes, and styles:
- Changing Text Content:
element.textContent = 'New text content';
- Modifying HTML:
element.innerHTML = '<strong>Bold text</strong>';
- Changing Attributes:
element.setAttribute('class', 'newClass');
- Modifying Styles:
element.style.color = 'red';
element.style.fontSize = '20px';
Creating and Removing Elements
You can dynamically add or remove elements from the DOM:
- Creating Elements:
let newDiv = document.createElement('div');
newDiv.textContent = 'New Div';
document.body.appendChild(newDiv);
- Removing Elements:
let elementToRemove = document.getElementById('removeMe');
elementToRemove.parentNode.removeChild(elementToRemove);
Event Handling
Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them.
Adding Event Listeners
You can use the addEventListener
method to handle events:
let button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log('Button clicked!');
});
Common Types of Events
- Mouse Events:
click
,dblclick
,mouseenter
,mouseleave
- Keyboard Events:
keydown
,keyup
,keypress
- Form Events:
submit
,change
,focus
,blur
- Window Events:
load
,resize
,scroll
Event Object
When an event occurs, the browser creates an event object with details about the event:
button.addEventListener('click', function(event) {
console.log('Button clicked at coordinates: ' + event.clientX + ', ' + event.clientY);
});
Practical Example: Interactive To-Do List
Let’s combine DOM manipulation and event handling to create a simple interactive to-do list:
<!DOCTYPE html>
<html>
<body>
<h2>My To-Do List</h2>
<input type="text" id="taskInput" placeholder="New task...">
<button id="addTask">Add Task</button>
<ul id="taskList"></ul>
<script>
let addTaskButton = document.getElementById('addTask');
let taskInput = document.getElementById('taskInput');
let taskList = document.getElementById('taskList');
addTaskButton.addEventListener('click', function() {
if (taskInput.value !== '') {
let newTask = document.createElement('li');
newTask.textContent = taskInput.value;
let deleteButton = document.createElement('button');
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', function() {
taskList.removeChild(newTask);
});
newTask.appendChild(deleteButton);
taskList.appendChild(newTask);
taskInput.value = '';
}
});
</script>
</body>
</html>
Practice Exercise
Enhance the to-do list application:
- Add a “Complete” button next to each task that, when clicked, strikes through the task text.
- Implement the ability to edit existing tasks.
- Add local storage functionality to persist tasks between page reloads.
Conclusion
This lesson covered the basics of DOM manipulation and event handling in JavaScript. These concepts are fundamental to creating interactive web applications. In the next lesson, we’ll explore asynchronous JavaScript, including promises and async/await syntax.
Remember to experiment with these concepts by modifying the example code and creating your own interactive web pages!