Introduction to the Document Object Model (DOM) and Dynamic Web Manipulation
Administrative Announcements
- Project 1 Deliverable: Project 1 deliverable 1 will be made available next week.
- Group Communication Coordination: If group members are non-responsive or communication channels are not established, contact Nilesh. He is responsible for group assignments and will resolve communication issues.
Foundational Review of Course Concepts
- Components of JavaScript Objects: Objects are primarily composed of two things:
- Properties: Data associated with the object.
- Methods: Functions or actions the object can perform.
- Built-in JavaScript Objects: Examples include:
- String: A sequence of characters.
- Map: A collection of keyed data items.
- Array: An ordered list of values.
- HTML Attribute Structure: Every HTML attribute consists of two main parts:
- Name: The identifier for the attribute (e.g.,
class, id). - Value: The specific assignment given to the name (e.g.,
"my-class").
The Window Object
- Definition: When a browser accesses an HTML document, it automatically creates a
window object representing the entire browser tab. - Global Scope: The
window object is a global variable. Methods associated with it, such as alert(), can be called directly without needing to prefix them with window.alert(). - Key Properties of the Window Object: These properties are themselves objects containing specific metadata:
- Location: Represents the URL of the webpage. It contains details like
origin, path name, and host name. - History: Specific to the active tab. It tracks the number of pages visited. The
length property indicates the number of visited sites in that session. If a user has only opened the current page, the length is 1. - Navigator: Contains information about the browser settings, operating system, and default language.
- Screen: Details the physical dimensions and resolution of the monitor or device being used.
- Document: Represents the entire HTML webpage and serves as the entry point for DOM manipulation.
The Document Object Model (DOM)
- Context: While HTML is static, the DOM is a "live" version that JavaScript can interact with and change in real-time.
- Hierarchical Structure: The DOM is organized in a parent-child tree structure.
- Root: The
<html> element acts as the root parent. - First Tier Children: The
<html> element typically contains two children: <head> and <body>. - Nesting Examples:
- A
<title> element is a child of the <head>. - If a
<div> contains <input> elements, the <div> is the parent and the <input> elements are the children. - Embedded content, such as an
<a> (anchor) or <img> (image) inside a <p> (paragraph), is represented as children of that paragraph node.
- Node Representation: Every component of the page is a node. There are four primary types:
- Document Node: The very top-level root.
- Element Node: Any HTML tag (e.g.,
<div>, <body>). - Text Node: Includes actual text content within tags and white spaces (new lines and spaces between elements) in the HTML file.
- Attribute Node: Includes attributes inside opening tags. Note: Unlike elements or text, these are not visually represented in the tree structure but remain part of the DOM.
Node Properties and Methods
- Generic Node Properties:
nodeType: Identifies if the node is an element, attribute, or text.firstChild / lastChild: Accesses the immediate first or last child of a parent node.parentNode: Accesses the node above the current one. The parent node of the document is the window object.nextSibling: Accesses the node at the same hierarchical level (e.g., <head> and <body> are siblings).textContent: Captures all text content and white space within an element.
- Generic Node Methods:
appendChild(): Adds a new child node to an existing element.hasChildNodes(): A Boolean check for children.hasAttributes(): A Boolean check for the presence of attributes.removeChild(): Deletes a child node.
- Specific Element Node Members:
- Properties:
tagName, id, and attributes. - Methods:
getAttribute() and setAttribute().
- Text and Attribute Object Details:
- Attribute objects return a
NamedNodeMap, which functions similarly to an array and allows access to name and value. - Text objects have a
data property to access text content and methods like appendData(), deleteData(), and insertData().
Dynamic HTML Manipulation
- Selecting Elements: There are 2 primary ways to grab elements using the
document object:getElementById("id_name"): Selects a single, specific element.getElementsByTagName("tag_name"): Returns an array-like collection of all elements with that tag. Because it returns multiple items, a for-loop is required to iterate through and manipulate each element (e.g., array[i].textContent).
- Modifying Content:
.textContent: Sets simple text content. Tags included in the string will be rendered as literal text, not HTML..innerHTML: Allows for the insertion of HTML tags that the browser will render as new children of the element.
- Event Handling: Interactive behaviors are managed by the
addEventListener() method, which takes 2 parameters:- The event type as a string (e.g.,
"click"). - A callback function defining the action to take upon the event.
- The Creating and Appending Process: To add an element via JavaScript:
- Use
document.createElement("tag") to create the node. - Assign content using
.textContent or .innerHTML. - Attach it to the page using
document.body.appendChild(newElement).
Managing CSS with JavaScript
- The Style Object:
- Accessing
element.style.property allows for direct modification of CSS properties. This overrides existing styles with inline CSS. - Naming Convention: Hyphenated CSS properties must be written in camelCase in JavaScript (e.g.,
background-color becomes backgroundColor).
- The ClassName Property:
- This approach involves changing the
element.className to match a predefined class in a CSS file. This is often cleaner than manipulating individual styles.
- Relative Positioning: To move an element across a page using properties like
left or top, the element's CSS position must be set to relative. Incremental movement can be achieved by updating a numeric variable and appending units (e.g., position + "px"). - Hiding vs. Removing:
element.remove() completely deletes the node from the DOM structure.- Hiding an element (e.g., using a class with
display: none) keeps the node in the DOM tree but makes it invisible, allowing it to be unhidden later.
Questions & Discussion
- Question: How do you select multiple
<div> elements as opposed to all of them at once? - Answer: One method is to use a for-loop to iterate through the results of
getElementsByTagName and select specific indices. Another more precise method is to assign unique ID values to the target <div> elements and select them individually using getElementById.