-
What is the DOM?
- DOM (Document Object Model) is an abstraction of the HTML document into a tree of objects.
- It allows dynamic interaction and manipulation of web content.
-
Static vs. Dynamic HTML
- Static HTML: Webpages remain unchanged regardless of user interactions.
- Dynamic HTML: Webpages update based on user actions, achieved using DOM manipulation.
-
Fetching Elements
- Methods to select elements:
document.querySelector()
β Selects the first matching element.document.querySelectorAll()
β Selects all matching elements (returns a NodeList).document.getElementById()
β Fetches element byid
.document.getElementsByClassName()
β Fetches elements by class name.document.getElementsByTagName()
β Fetches elements by tag name.
- Methods to select elements:
-
DOM Manipulation
- Accessing and modifying elements dynamically:
- Inner Content:
.innerHTML
β Get or set HTML content..textContent
β Get or set text content.
- Styling:
.style
β Modify inline CSS properties..classList
β Add, remove, or toggle CSS classes.
- Creating/Deleting Elements:
document.createElement()
β Create new elements..appendChild()
β Add child elements..removeChild()
β Remove child elements.
- Inner Content:
- Accessing and modifying elements dynamically:
-
Event Handling
- Events enable interaction between users and webpages.
- Common methods:
.addEventListener(event, callback)
β Attach a handler to an event.- Inline event attributes (e.g.,
onclick
) β Not recommended for modern applications.
Example:
const button = document.querySelector("button"); button.addEventListener("click", () => { alert("Button clicked!"); });
-
Event Object
- Provides additional details about an event.
- Example:
document.addEventListener("click", (event) => { console.log(event.target); // Logs the clicked element });
-
Tasks and Practical Applications
- Accessing Elements: Fetch elements and change their content dynamically.
- Dynamic Styling: Modify styles or toggle classes based on user interactions.
- Creating and Deleting Elements: Allow users to add/remove content on the fly.
-
DOM Basics:
- Understood how to access and modify HTML elements using DOM methods.
- Learned how to handle events and respond to user interactions dynamically.
-
Event Handling:
- Explored event-driven programming and used event listeners for interaction.
- Gained insights into the
Event
object for advanced event handling.
- DOM is essential for dynamic interaction in web applications.
- Event handling bridges the gap between static content and user interactions.
- With DOM manipulation and event listeners, we can create highly interactive web experiences.
π― Practice Exercise:
- Try building a simple webpage with:
- A button to toggle the theme (dark/light).
- A form with input validation.
- A list where users can add or remove items dynamically.
Keep experimenting and happy coding! π