Day 17: DOM Manipulation
Quiz aheadIntroduction
Welcome to this tutorial on JavaScript DOM manipulation! In this session, we'll explore how to interact with HTML elements using JavaScript, enabling you to create dynamic and interactive web applications.
How CSS Sees HTML (CSS Box Model)
The CSS Box Model is fundamental to understanding how CSS layouts work. Each HTML element is represented as a box with the following properties:
- Content: The actual content of the box, such as text or images.
- Padding: The space between the content and the border, which adds space inside the box.
- Border: A border that surrounds the padding (if any).
- Margin: The space outside the border, separating the box from other elements.
Understanding the Box Model helps you manage layout and spacing effectively.
How JS Sees HTML (The DOM)
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects. Each HTML element is an object, allowing JavaScript to manipulate the content and structure dynamically.
Types of DOM Manipulation Methods
There are several methods to manipulate the DOM:
- Creating elements:
document.createElement()
- Inserting elements:
appendChild()
,insertBefore()
- Modifying elements: Changing attributes or styles
- Removing elements:
removeChild()
,remove()
About the Developer Console
The Developer Console is a powerful tool for debugging. You can use console.log()
to print messages or variable values, helping you understand the flow of your program. Open it by right-clicking on your webpage and selecting "Inspect" or pressing F12
.
Selecting (Finding) Elements
To manipulate elements, you first need to select them. Common methods include:
document.getElementById(id)
: Selects an element by its ID.document.getElementsByClassName(className)
: Selects elements by their class.document.querySelector(selector)
: Selects the first matching element.document.querySelectorAll(selector)
: Selects all matching elements.
Explaining JS Window and Document Objects
- Window Object: Represents the browser window and contains methods to control the entire window.
- Document Object: Represents the web page and serves as an entry point for accessing and manipulating the DOM.
Creating Elements
You can create new HTML elements using:
const newElement = document.createElement('div');
newElement.textContent = 'Hello, World!';
This creates a new <div>
element with the text "Hello, World!"
.
Attach Elements to DOM Tree
To add the newly created element to the DOM, use:
document.body.appendChild(newElement);
Modifying Element Text
To change the text of an existing element:
const existingElement = document.getElementById('myElement');
existingElement.textContent = 'New Text!';
Reading Element Text
To read the text of an element, you can access its textContent property:
const elementText = existingElement.textContent;
console.log(elementText);
Removing Elements
This completely removes the specified element from the document.
const elementToRemove = document.getElementById('removeMe');
elementToRemove.remove();
Event Management
Event management allows you to respond to user interactions, such as clicks or keyboard events. You can add event listeners to elements to trigger functions when events occur.
const addButton = document.getElementById('addButton');
addButton.addEventListener('click', function() {
// Logic to add a new item
});
Functions
Functions are reusable blocks of code. You can define functions to encapsulate logic and call them when needed:
function addItem() {
// Code to add an item
}
AddEventListener
Use addEventListener() to listen for events:
const button = document.getElementById('addButton');
button.addEventListener('click', addItem);
This attaches the addItem
function to the button click event.
AddEventListener Callback Function
You can pass a callback function directly to addEventListener()
:
button.addEventListener('click', function() {
console.log('Button clicked!');
});
This changes the background color of the element.
Mini Practical Project
Let’s create a simple project where we build a list of items dynamically using the techniques we've learned. You can set up an input field to add items to a list and buttons to modify or remove them.
Assignment 17:
Let’s create a simple project where we build a list of items dynamically using the techniques we've learned. You can set up an input field to add items to a list and buttons to modify or remove them.
-
HTML Structure: Create a basic HTML file that includes:
- An input field for users to type in new items.
- A button to add the item to the list.
- An empty list (e.g.,
<ul>
or<ol>
) to display the items.
-
JavaScript: Write functions to handle:
- Adding items to the list when the button is clicked.
- Removing items from the list.
- Modifying existing items (e.g., editing them).
-
Styling: Use CSS to enhance the appearance of the list and make the interface user-friendly.