Share
Explore

s24 MADS 4007 Tuesday May 14

Learning outcomes:

Introduction to the HTML Document Object Model and the BOM Browswer Object Model
Manipulating the DOM (collections of tag) with JavaScript
Selecting a NODE (HTML Element) using document.querySelector
Manipulating the HTML Element using JavaScript APIs
Changing DOM Node attributes (color, text)
Creating and Deleting Nodes (html tags in memory) with JavaScript APIs

Navigating the Web with JavaScript – An Introduction to the DOM and BOM

Introduction

Today's lecture focuses on two core web development concepts: the HTML Document Object Model (DOM) and the Browser Object Model (BOM).
Understanding these models is essential for manipulating web pages dynamically using JavaScript.

Understanding the DOM and BOM

1. HTML Document Object Model (DOM)

The DOM provides a structured representation of the document (HTML) as a tree of objects.
The objects are NODES (nodes =vertices in the edged graph data structure which is the HTML DOM) in the HTML Document Object Tree.
megaphone

In the HTML Document Object Model (DOM), a "Node" represents a single point in the document tree and serves as a primary data structure for the entire document. It can be one of several different types of elements such as an element node, text node, or attribute node, among others, depending on its role and the data it contains.


Here's a breakdown of the different types of nodes and their functions:

Types of Nodes

Element Node: Represents each element in an HTML document.
These nodes are defined by tags and can contain attributes, text, and other elements. They form the structure of an HTML page. For example, <div>, <p>, and <a> tags are represented as element nodes in the DOM.
Text Node: Contains the actual text inside elements and is always a child of an element node. It does not contain any other nodes beneath it. For example, in <p>Hello, World!</p>, the string "Hello, World!" is contained within a text node.
Attribute Node: Attributes of an element such as class, id, style, etc., are represented as attribute nodes. They are associated with an element node and contain additional data about the element, like configuration or properties.
Comment Node: Represents comments in the HTML document, which appear as <!-- comment --> in the HTML code.
Document Node: The top-level node that represents the entire document. It acts as a root from which all other nodes branch out. <html>
DocumentType Node: Defines the type of document and can be used to specify the HTML document type declaration, for example, <!DOCTYPE html>.

Importance of Nodes in the DOM

Nodes are crucial for the DOM's functioning because they allow the document to be manipulated as a structured tree.
By understanding and using these nodes:
Programmatic Access and Manipulation: Nodes provide hooks that programming languages like JavaScript can access or manipulate, changing the content, structure, and style of a webpage dynamically.
Event Handling: Nodes can have event handlers attached, making it possible to implement interactive behaviors and respond to user actions like clicks, mouse movements, and keyboard input.
Hierarchical Structure: The node tree structure enables developers to navigate around the document efficiently, select elements, change their attributes, and manipulate their positions: AND update all over nodes which may be the recipients of state updates as a result of some node being changed.
Understanding nodes and their relationships within the DOM is fundamental for web developers looking to create, modify, and interact with web pages programmatically using languages like JavaScript.
This knowledge is key to developing dynamic and responsive web applications.
These objects can be manipulated with JavaScript, allowing dynamic changes to the content, structure, state, and style of a webpage.

2. Browser Object Model (BOM)

The BOM allows JavaScript to "talk" to the browser, providing access to browser-related functions independent of the content of the web pages. BOM operations include interacting with the URL, creating new windows, and more.

Manipulating the DOM with JavaScript

JavaScript enables the dynamic interaction with the DOM, allowing for real-time content updates, element style changes, and much more. Key methods include:
Accessing elements
Modifying elements
Creating or deleting elements

Selecting Nodes Using document.querySelector

document.querySelector is a powerful method that returns the first element that matches a specified selector(s).
Here's how it works:
const element = document.querySelector('.my-class'); // Selects the first element with the class 'my-class'

Manipulating HTML Elements with JavaScript APIs

Once an element is selected, you can use JavaScript to manipulate its properties and methods to change the document dynamically:
Changing text: element.textContent = 'New text';
Changing style: element.style.color = 'blue';

Changing DOM Node Attributes

Attributes such as class, id, style, and custom data attributes can be manipulated to affect the behavior and presentation of elements:
element.setAttribute('class', 'new-class');

Creating and Deleting Nodes with JavaScript APIs

JavaScript can create new nodes using document.createElement and remove them using removeChild or remove:
Creating an element: const newDiv = document.createElement('div');
Deleting an element: element.remove(); // Removes the element from the DOM

error

What is a Node in the html document object model

In the HTML Document Object Model (DOM), a "Node" represents a single point in the document tree and serves as a primary data structure for the entire document. It can be one of several different types of elements such as an element node, text node, or attribute node, among others, depending on its role and the data it contains. Here's a breakdown of the different types of nodes and their functions:

Types of Nodes

Element Node: Represents each element in an HTML document. These nodes are defined by tags and can contain attributes, text, and other elements. They form the structure of an HTML page. For example, <div>, <p>, and <a> tags are represented as element nodes in the DOM.
Text Node: Contains the actual text inside elements and is always a child of an element node. It does not contain any other nodes beneath it. For example, in <p>Hello, World!</p>, the string "Hello, World!" is contained within a text node.
Attribute Node: Attributes of an element such as class, id, style, etc., are represented as attribute nodes. They are associated with an element node and contain additional data about the element, like configuration or properties.
Comment Node: Represents comments in the HTML document, which appear as <!-- comment --> in the HTML code.
Document Node: The top-level node that represents the entire document. It acts as a root from which all other nodes branch out.
DocumentType Node: Defines the type of document and can be used to specify the HTML document type declaration, for example, <!DOCTYPE html>.

Importance of Nodes in the DOM

Nodes are crucial for the DOM's functioning because they allow the document to be manipulated as a structured tree. By understanding and using these nodes:
Programmatic Access and Manipulation: Nodes provide hooks that programming languages like JavaScript can access or manipulate, changing the content, structure, and style of a webpage dynamically.
Event Handling: Nodes can have event handlers attached, making it possible to implement interactive behaviors and respond to user actions like clicks, mouse movements, and keyboard input.
Hierarchical Structure: The node tree structure enables developers to navigate around the document efficiently, select elements, change their attributes, and manipulate their positions.
Understanding nodes and their relationships within the DOM is fundamental for web developers looking to create, modify, and interact with web pages programmatically using languages like JavaScript. This knowledge is key to developing dynamic and responsive web applications.

Theoretical Introduction to JavaScript APIs for Node Manipulation via the Browser Object Model
JavaScript APIs provide a programmatic interface for developers to interact with and manipulate the web document's structure, content, and presentation through the Document Object Model (DOM) using the capabilities provided by the Browser Object Model (BOM). Understanding these APIs is crucial for dynamic and responsive web development.

Browser Object Model (BOM)

The Browser Object Model is not standardized like the DOM; however, it includes objects that represent the browser window and provide functionality that allows manipulation of the browser itself. Common uses of the BOM include managing browser windows, the history of the browser, the screen's properties, and more. Importantly, the BOM provides the context in which the DOM operates, and it gives JavaScript a way to interact with the browser outside the constraints of the web page content.

JavaScript APIs for DOM Manipulation

JavaScript offers a suite of APIs to create, modify, and delete nodes within the DOM. These operations are essential for dynamic content manipulation, allowing web applications to react to user inputs and other real-time events. Here's an overview of these capabilities:

1. Document Interface

Purpose: Represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree.
Common Methods:
document.createElement(): Creates a new element node.
document.createTextNode(): Creates a new text node.
document.querySelector(): Returns the first element within the document that matches the specified group of selectors.

2. Element Interface

Purpose: Represents an element in an HTML or XML document.
Common Methods:
element.appendChild(): Adds a node as the last child of a node.
element.removeChild(): Removes a child node from the DOM.
element.replaceChild(): Replaces one child node of the specified existing child with a new node.
element.getAttribute(): Accesses the value of a specified attribute on the element.
element.setAttribute(): Sets the value of an attribute on the specified element.

3. Node Interface

Purpose: Serves as an interface from which various types of DOM API objects inherit and thus shares methods and properties across those object types.
Common Methods:
node.appendChild(): Adds a new child node to a node as the last child.
node.cloneNode(): Clones a node.
node.insertBefore(): Inserts a node before the reference node as a child of a specified parent node.

4. Event Handling

Integration with BOM: JavaScript uses the BOM to handle user interactions such as clicks, form submissions, and keyboard events, allowing dynamic responses to these actions.
Event Listener Methods:
addEventListener(): Attaches an event handler to the specified element without overwriting existing event handlers.
removeEventListener(): Removes an event handler that has been attached with the addEventListener() method.
Through the integration of DOM manipulation techniques via JavaScript and the contextual capabilities provided by the BOM, developers can create highly interactive and responsive web applications. This theoretical foundation supports a wide range of practical applications, from simple dynamic content updates to complex web applications that react seamlessly to user inputs and browser events. Understanding and leveraging these APIs is fundamental to modern web development, ensuring that applications are both functional and engaging.

Is the BOM generated by the Web Browser when it renders and HTML DOM?

No, the Browser Object Model (BOM) is not generated by the web browser in the same way as the HTML Document Object Model (DOM).
Instead, the BOM and DOM serve different purposes and exist as separate parts of the web browser's architecture.

Understanding the BOM

The Browser Object Model (BOM) is primarily concerned with browser components that are not necessarily part of any specific document's content being displayed in the browser. It includes:
The window object, which serves as the global context of JavaScript execution and contains methods for opening, closing, resizing, and moving browser windows.
Navigation objects such as window.location, which can manipulate the URL.
Browser history management through window.history.
Screen dimensions and colors through window.screen.
Timers through methods like setTimeout() and setInterval().

Understanding the DOM

In contrast, the Document Object Model (DOM) specifically represents the content of a webpage, structured as a tree of nodes that includes elements, text, and other types of nodes.
The DOM is generated by the browser as it parses HTML documents, turning markup into an interactive model that scripts can manipulate.

Relationship Between BOM and DOM

While the BOM provides a context in which the DOM operates, it is not dependent on the specific details of the DOM.
The BOM is generally consistent across all web pages in a browser because it interacts with the browser interface rather than the content of a specific document.
However, one could argue that the DOM is part of the BOM since the DOM can be accessed through the window.document property, making it a component within the broader browser context.
In essence, while the BOM can affect how documents are loaded, displayed, and interacted with (for instance, through manipulation of the window size or navigation actions), it does not "generate" the DOM. The DOM is instead constructed from the HTML and other resources of the web page as parsed by the browser's HTML parser.

The dom lives in the html pages. Where does the BOM live?

The Browser Object Model (BOM) does not "live" in a specific document or webpage like the DOM. Instead, it exists as part of the browser's environment itself, serving as a layer that provides JavaScript access to browser functionality independent of the content displayed.
Think about the BOM as being a layer of Velcro wrapped around the HTML DOM: the sticky spikes give us a handle of control to connect to DOM elements.
Thinking of the Browser Object Model (BOM) as a layer of Velcro wrapped around the HTML Document Object Model (DOM) gives us a visualization to conceptualize the relationship and interaction between these the DOM and the ‘control grid” we can hook into with JavaScript.

Velcro Analogy Explained

Velcro Base (BOM Layer):
The base or backing of the Velcro represents the BOM. Just like Velcro has a foundation that supports the hooks, the BOM provides foundational support for interactions with the browser. This includes managing windows, navigating through the browser history, handling URL changes, and more.
Sticky Spikes (BOM Features):
The hooks or spikes on the Velcro symbolize the various features and functionalities of the BOM that "stick" to or interact with the DOM elements. These features give you the "handles" or control points to manipulate browser behavior, like opening new tabs, resizing windows, or even refreshing the page, which directly or indirectly affects the DOM.
DOM as the Surface:
The DOM can be likened to the surface that the Velcro sticks to. It represents the structure and content of the web page, which the BOM can interact with but is distinct in its composition. The DOM provides a tangible entity that the BOM’s functionalities can latch onto, affecting how the HTML elements are displayed, manipulated, and interacted with.

Practical Implications of the Analogy

Interactivity: Just as Velcro allows for easy and adjustable attachment and detachment, the BOM provides mechanisms to flexibly connect with and manipulate the DOM elements. This can be seen in how JavaScript uses BOM functions to dynamically update the DOM based on user interactions or browser events.
Accessibility: The hooks on Velcro are accessible and straightforward to use, mirroring how the BOM's features are designed to be directly accessible via global JavaScript objects and methods. This accessibility facilitates the rapid development and implementation of interactive web features.
Control and Flexibility: Velcro offers a level of control and flexibility in how tightly or loosely it adheres to the surface. Similarly, the BOM allows developers varying degrees of control over the browser and the web page environment, from subtly changing the current URL to aggressively manipulating window sizes or forcibly redirecting users to different sites.
This analogy underscores the functional relationship between the BOM and DOM, highlighting how the BOM encompasses and extends the capabilities of web browsers to interact with the structured content provided by the DOM. It provides a clear, illustrative way to convey the practical and dynamic interactions that make modern web applications both powerful and user-friendly.

Characteristics of the BOM:

Browser-wide Scope: The BOM provides objects and functions that interact with the browser, such as managing windows, the URL, and the browser history. Unlike the DOM, which is tied to the specific content of a webpage, the BOM's scope is the entire browser environment.
Global Access: You can access BOM features using the global window object in JavaScript, which represents the browser window and serves as the top-level object in the scripting environment. All global JavaScript objects, functions, and variables are part of the window object.
Consistent Presence: The BOM is consistently available across all web pages loaded in the browser. It is a part of every browser session and is not re-created with each new webpage; instead, it persists as long as the browser window is open.

How the BOM Functions:

Operational Basis: The BOM operates at a higher level than the DOM. It allows scripts to interact with the browser itself—for example, to open new tabs or windows, manipulate the size and positioning of the browser window, or query the screen's resolution.
Independent but Interconnected: While the BOM and DOM are separate, they interact closely. For instance, the window.document property is part of the BOM and points to the DOM of the current page, linking the browser's functionality directly with the content it displays.
In summary, while the DOM is specific to each web page and represents its content structure, the BOM lives at the browser level, providing mechanisms to interact with and control the browser environment and maintain functionality that affects how web pages are loaded, displayed, and interacted with.
This makes it a fundamental aspect of how web applications create and manage interactive sessions with users.

Browser Object Model (BOM) Entities

The BOM diagram would ideally be organized around the window object, which is central to the BOM as it represents the browser window. From this central node, branches would extend to various other BOM entities and functionalities.
image.png
Window Object: At the center of the diagram, as it is the global object in client-side JavaScript that represents the window containing the DOM document.
Properties:
window.document: Points to the DOM of the page.
window.location: Contains information about the current URL.
window.history: Allows manipulation of the browser session history.
window.screen: Provides information about the user's screen, like its resolution.
window.navigator: Holds information about the browser itself.
window.localStorage and window.sessionStorage: For storing information locally in the browser.
Document:
Directly connected to the window object, as window.document.
Location:
Showing methods like href, reload(), replace(), and properties that describe the URL.
History:
Methods such as back(), forward(), go(), which allow navigation through user history.
Screen:
Details like width, height, colorDepth, and pixelDepth.
Navigator:
Represents information about the browser, with properties like userAgent, appName, appVersion, language.
Storage:
Split into localStorage and sessionStorage, illustrating methods like setItem(), getItem(), removeItem(), and clear().
Additional Objects:
Timers: setTimeout(), setInterval(), clearTimeout(), clearInterval().
Alerts/Popups: alert(), confirm(), prompt().
Each of these main entities branch out from the central window node, with lines connecting them back to show they are properties or methods accessible from the window object.
This diagram can serve as a conceptual map to understand how the various BOM features interact with each other and provide functionality to web applications beyond the content displayed by the DOM.

Lab Drills: Applying DOM and BOM Techniques

These drills are designed to solidify your understanding and practical skills in manipulating the DOM and using the BOM effectively.
By mastering these foundational tasks, you gain the ability to create interactive and dynamic web applications.
Each task is designed to challenge your understanding and encourage practical application, ensuring you build strong web development skills.

Drill 1: Dynamic Content Update

Objective: Practice using document.querySelector and manipulate text content.
Task: Create a webpage with a paragraph element. Use JavaScript to update the text when a button is clicked.
megaphone

Create a DOM with document.querySelector to select HTML elements and manipulate their content dynamically with JavaScript. Below, you will find detailed explanations of the HTML structure and JavaScript functions used in each example.

Example 1: Basic Text Update

HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Content Update</title>
</head>
<body>
<p id="textDisplay">Original Text</p>
<button id="updateButton">Change Text</button>

<script src="script.js"></script>
</body>
</html>

JavaScript (script.js)

document.getElementById('updateButton').addEventListener('click', function() {
const paragraph = document.querySelector('#textDisplay');
paragraph.textContent = 'Updated Text: Hello, World!';
});

In this example, when the user clicks the "Change Text" button, the text content of the paragraph with the id textDisplay is updated. document.querySelector is used to select the paragraph element by its ID.

Example 2: Random Greeting Generator

Let's make it more interesting by updating the paragraph with a random greeting from an array of greetings whenever the button is clicked.
HTML
Remains the same as in Example 1.
JavaScript
const greetings = [
'Hello, World!',
'Hi there!',
'Welcome to our site!',
'Good day!',
'Greetings, traveler!'
];

document.getElementById('updateButton').addEventListener('click', () => {
const randomIndex = Math.floor(Math.random() * greetings.length);
const paragraph = document.querySelector('#textDisplay');
paragraph.textContent = greetings[randomIndex];
});

This script enhances the button's functionality by displaying a random greeting from the greetings array each time it's clicked, demonstrating how document.querySelector can be used repeatedly to manipulate the same DOM element in various ways.

Example 3: Changing Styles Dynamically

Add a bit more interactivity by not only changing text but also changing styles dynamically.
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic Style Update</title>
</head>
<body>
<p id="textDisplay" style="color: blue;">Original Text</p>
<button id="updateButton">Change Text and Color</button>

<script src="script.js"></script>
</body>
</html>

JavaScript

document.getElementById('updateButton').addEventListener('click', () => {
const paragraph = document.querySelector('#textDisplay');
const isBlue = paragraph.style.color === 'blue';
paragraph.style.color = isBlue ? 'red' : 'blue';
paragraph.textContent = isBlue ? 'Text is now red!' : 'Text is back to blue!';
});

In this example, the script toggles the color and text content of the paragraph each time the button is clicked, demonstrating how document.querySelector can be used to manipulate both the text and style properties of an element.

Drill 2: Style Manipulator

Objective: Learn to dynamically change the style of an element.
Task: Provide a list of items and a set of buttons that change the background color of the list items when clicked.

megaphone

For Drill 2, titled "Style Manipulator," we will create an interactive example where users can change the background color of list items using buttons.

This drill will further demonstrate how to use document.querySelector to select elements and manipulate their styles dynamically with JavaScript.

HTML Setup

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Style Manipulator</title>
</head>
<body>
<ul id="itemList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<button id="redButton">Red</button>
<button id="greenButton">Green</button>
<button id="blueButton">Blue</button>

<script src="script.js"></script>
</body>
</html>

JavaScript for Dynamic Style Manipulation

In the JavaScript part, we'll add event listeners to the buttons that, when clicked, will change the background color of all list items.
// Select all the list items
const items = document.querySelectorAll('#itemList li');

// Function to change color of all items
function changeItemColor(color) {
items.forEach(item => {
item.style.backgroundColor = color;
});
}

// Attach event listeners to buttons
document.getElementById('redButton').addEventListener('click', () => changeItemColor('red'));
document.getElementById('greenButton').addEventListener('click', () => changeItemColor('green'));
document.getElementById('blueButton').addEventListener('click', () => changeItemColor('blue'));

Explanation

HTML: The HTML structure consists of an unordered list with three items and three buttons. Each button is intended to change the background color of all list items to a specific color when clicked.
JavaScript:
Selecting Elements: We use document.querySelectorAll to select all the list items. This method returns a NodeList of elements that match the specified selector, allowing us to apply styles to multiple elements simultaneously.
Function for Changing Colors: The changeItemColor function takes a color value as an argument and applies it as the background color to each item in the NodeList. This demonstrates the power of NodeLists and how they can be iterated with forEach to apply changes to multiple elements.
Event Listeners: We add click event listeners to each button. When a button is clicked, the changeItemColor function is called with the corresponding color. This demonstrates how event listeners can interact with DOM elements and trigger style changes based on user interactions.

Enhancing the Example (enhancement lab)

To make this example even more interesting, consider adding the following features:
Random Color Button: Add a button that changes the background color of items to a random color from a predefined list.
Reset Button: Implement a button to clear all custom styles and reset the list items to their default state.
Interactive Feedback: Provide visual feedback (like a border glow) when an item's color changes, indicating the change more clearly to the user.
This setup provides a clear demonstration of how to manipulate styles dynamically in the DOM using JavaScript

Drill 3: Attribute Changer

Objective: Manipulate attributes of HTML elements using JavaScript.
Task: Create an input form with a submit button. Use JavaScript to change the placeholder text of the input when hovered.
error

For Drill 3, titled "Attribute Changer," we'll focus on dynamically manipulating the attributes of an HTML element using JavaScript. Specifically, we'll create an input form with a submit button and change the placeholder text of the input when it is hovered over. This example will illustrate the use of document.querySelector to modify element attributes.

HTML Setup


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Attribute Changer</title>
</head>
<body>
<form>
<input type="text" id="inputField" placeholder="Hover over me!">
<button type="submit">Submit</button>
</form>

<script src="script.js"></script>
</body>
</html>

JavaScript for Changing Attributes

We will use JavaScript to add event listeners to the input field that change its placeholder attribute when hovered over and restore it when the mouse leaves.

document.addEventListener('DOMContentLoaded', function() {
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.