Session 11 DOM Manipulation
Session 11 DOM Manipulation
● Understand the Document Object Model (DOM) and its role in web development.
● Learn how to select and modify HTML elements using JavaScript.
● Introduction to event handling (clicks, keypresses, etc.).
What is the DOM?
● Definition: The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of
an HTML document as a tree of objects that can be manipulated using JavaScript.
● Why is the DOM Important?
○ Allows developers to interact with and manipulate the structure, style, and content of a webpage.
○ When the DOM is updated, the changes are reflected on the page instantly.
● Visual Representation:
○ HTML elements (like <div>, <p>, <button>) are nodes in the DOM tree.
○ JavaScript can traverse, add, modify, or remove these nodes.
The Structure of the DOM
Key DOM Objects:
● <body>
○ <h1> → "Hello, World!"
○ <p> → "This is a paragraph."
Selecting HTML Elements in JavaScript
How to Access DOM Elements:
Common Methods:
Removing Elements:
● An event is an action that occurs on a webpage, like a button click, keypress, or page load.
● Event handling allows developers to create interactive websites, responding to user actions in real-time.
Common Events:
● Use the addEventListener() method to attach a function (called a callback) to an element that executes when the event
occurs.
Example
Handling Different Events
Click Event Example:
Instructions:
Overwriting Existing Content: When using innerHTML, be cautious as it can overwrite existing content.
Forgetting to Attach Event Listeners: Always ensure that event listeners are added after the elements are loaded.
Debugging DOM Manipulation
Using the Console: Use the browser's developer console to inspect the DOM and test JavaScript code.
Check for Errors: Look for common errors like null or undefined when selecting elements.
Summary
What We Learned Today: