Chapter 6: JavaScript HTML DOM
55 slides · use ←/→ or Space to navigate, F for fullscreen.
Jump to a lesson deck: Introduction to the DOM The HTML DOM: Objects, Properties & Methods DOM Tree, Nodes & Relationships Finding & Accessing HTML Elements Changing HTML Content & CSS Styles DOM Events & Event Handling The addEventListener() Method onLoad, Radio Buttons & JS Event Properties Form Validation with Events Browser Object Model (BOM)
Chapter 6: JavaScript HTML DOM
The Document Object Model — how JavaScript finds, reads, changes and reacts to every element on a web page.
Introduction to the DOM
What the Document Object Model is and the W3C DOM standard.
What is the Document Object Model (DOM)?
- The DOM is a programming interface for HTML and XML documents.
- It represents the document's content as a structured, hierarchical set of objects.
- It allows developers to access and modify content, structure and style dynamically.
- It is represented as a tree-like structure — every element, attribute and text is a node.
- The top-level node is the
documentobject, representing the entire page. - It is accessible and manipulable using programming languages such as JavaScript.
The W3C DOM Standard
“The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.”
| Part | Purpose |
|---|---|
| Core DOM | Standard model for all document types. |
| XML DOM | Standard model for XML documents. |
| HTML DOM | Standard model for HTML documents. |
Activity — complete the code
Complete the script that finds, changes and styles an element.
<html><body><p id="intro">Hello World!</p><script>// 1. Find the elementvar x = document.("intro");// 2. Change its contentx. = "The DOM is a programming interface.";// 3. Change its stylex.style. = "red";</script></body></html>
The HTML DOM: Objects, Properties & Methods
The HTML DOM object model, its hierarchy, and the properties/methods programming interface.
What is the HTML DOM?
A standard object model and programming interface for HTML. It defines:
- HTML elements as objects
- Properties of all HTML elements
- Methods to access all HTML elements
- Events for all HTML elements
When a web page loads, the browser creates a DOM of the page. Every HTML element is accessible in JavaScript through the DOM. The HTML DOM is platform and language independent.
The HTML DOM Object Hierarchy
window (outermost — represents the browser window)
└─ document (each loaded HTML document)
└─ html
├─ head
└─ body
└─ form
└─ form controls (checkbox, text, ...)
The tree structure helps JavaScript navigate and manipulate every element on the page.
HTML DOM Objects — Core Reference
| Object | Represents |
|---|---|
| Document | The entire HTML document |
| Event | Mouse clicks, key presses |
| Form & Form Input | Form elements |
| Anchor | Hyperlinks (<a>) |
| Frame / Frameset / IFrame | Frames |
| Additional object | Represents |
|---|---|
| Image | HTML <img> elements |
| Location | Current page URL |
| Navigator | Browser information |
| Option & Select | Drop-down lists |
| Screen | Screen size and resolution |
| Table / TableRow / TableData | Table structures |
| Window | Browser window / frame |
Properties and Methods
Methods are actions you can perform on HTML elements. Properties are values of HTML elements that you can get or set.
var txt = document.getElementById("intro").innerHTML;
// └── METHOD ────────────────┘ └─ PROPERTY ─┘ Activity — complete the code
Distinguish methods from properties and navigate the object hierarchy.
// getElementById() is a// innerHTML is a// Object hierarchy: window -> -> html -> body// Property exampledocument.getElementById("demo").style. = "25px";
DOM Tree, Nodes & Relationships
The document node tree, node types, and parent/child/sibling relationships.
The HTML DOM Document Node Tree
The node tree starts at the root node and branches to text nodes at the lowest level.
<html>
<head>
<title>My title</title>
</head>
<body>
<a href="#">My link</a>
<h1>My header</h1>
</body>
</html>
document
└─ html (element)
├─ head (element)
│ └─ title (element) └─ text: "My title"
└─ body (element)
├─ a (element, attribute: href) └─ text: "My link"
└─ h1 (element) └─ text: "My header"
W3C HTML DOM Node Types
| Node type | Meaning |
|---|---|
| Document node | The entire HTML document (the root). |
| Element node | Every HTML element (<p>, <div>, <span>...). |
| Text node | The text content inside HTML elements. |
| Attribute node | Every HTML attribute (id, class, href...). |
| Comment node | All HTML comments. |
Node Relationships: Parent, Child, Sibling
- Root node — the top node in the tree (has no parent).
- Parent — every node has exactly one parent, except the root.
- Children — a node can have zero or more child nodes.
- Siblings — nodes that share the same parent.
Example
<html>
<head><title>DOM Tutorial</title></head>
<body>
<h1>DOM Lesson One</h1>
<p>Hello world!</p>
</body>
</html>
<html>is the root node (no parent).<html>is the parent of<head>and<body>.<head>is the first child of<html>;<body>is the last child.<title>has a text node: "DOM Tutorial".<body>has two children:<h1>and<p>; they are siblings.
Activity — complete the code
Complete the node types and relationships.
<!-- The entire document is a node --><!-- <p> is an node --><!-- The text inside <p> is a node --><!-- id="x" is an node --><!-- Relationships --><!-- <html> is the node (it has no parent) --><!-- <head> and <body> are of <html> -->
Finding & Accessing HTML Elements
getElementById, getElementsByTagName, getElementsByClassName, querySelectorAll and form collections.
The Document Object: Finding HTML Elements
To access any element, always start with the document object.
| Method | Description |
|---|---|
document.getElementById(id) | Find an element by its id attribute. |
document.getElementsByTagName(name) | Find elements by HTML tag name. |
document.getElementsByClassName(name) | Find elements by CSS class name. |
document.querySelectorAll(selector) | Find elements by CSS selector. |
document.forms[name].elements[i].value | Access HTML form object collections. |
Finding Elements by ID — getElementById()
Returns the element whose id matches the given string. The id should be unique; returns null if not found.
<p id="intro">Hello World!</p>
<script>
var x = document.getElementById("intro");
document.write("Paragraph text: " + x.innerHTML);
</script>
Finding Elements by Tag Name — getElementsByTagName()
Returns an HTMLCollection of all elements with the given tag name — access using a zero-based index.
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<script>
var x = document.getElementsByTagName("p");
document.write("First paragraph: " + x[0].innerHTML);
</script>
Finding Elements by Class Name — getElementsByClassName()
<p class="intro">The DOM is very useful.</p>
<p class="intro">This demonstrates getElementsByClassName.</p>
<p id="demo"></p>
<script>
var x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML = "First intro paragraph: " + x[0].innerHTML;
</script>
Finding Elements by CSS Selector — querySelectorAll()
Selects all elements matching a CSS selector string and returns a static NodeList — more powerful and flexible than the class/tag methods.
<p class="intro">The DOM is very useful.</p>
<p class="intro">This demonstrates querySelectorAll.</p>
<p id="demo"></p>
<script>
var x = document.querySelectorAll(".intro");
document.getElementById("demo").innerHTML = "First match: " + x[0].innerHTML;
</script>
Finding Elements via HTML Object Collections
<form id="frm1">
First name: <input type="text" name="fname" value="Donald">
Last name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
var x = document.forms["frm1"];
var text = "";
for (var i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script> Activity — complete the code
Complete the four ways of finding elements.
// By idvar x = document.("intro");// By tag name (returns a collection)var y = document.("p");document.write(y[0].innerHTML);// By class namevar z = document.("intro");// By CSS selector (returns a NodeList)var w = document.(".intro");
Changing HTML Content & CSS Styles
document.write(), the innerHTML property, and changing styles via the DOM.
Writing to the HTML Output Stream — document.write()
- Outputs text directly into the HTML stream during page load.
- Can include HTML tags for formatting.
- Warning: calling it after the page has loaded overwrites the entire page.
document.write("Hello World!"); // plain text
document.write("<h1>Hello!</h1>"); // renders as an H1 heading
Changing HTML Content — the innerHTML Property
The easiest way to get or set element content. It can change any HTML element, including <html> and <body>, and is preferred over document.write() for changes after page load.
<p id="demo">Hello World!</p>
<script>
// Replace the paragraph content
document.getElementById("demo").innerHTML = "New text!";
</script>
Changing CSS Styles via the DOM
Syntax: document.getElementById(id).style.property = "value".
// Change text colour and font size
document.getElementById("p1").style.color = "red";
document.getElementById("p1").style.fontSize = "xx-large";
// Hide or show an element
document.getElementById("myDiv").style.display = "none"; // hide
document.getElementById("myDiv").style.display = "block"; // show
// Change the page background
document.body.style.backgroundColor = "#f0f4f8"; Activity — complete the code
Complete the content and style changes.
// Write into the output stream during page loaddocument.("<h1>Hello!</h1>");// Replace an element contentdocument.getElementById("demo"). = "New text!";// Change a CSS styledocument.getElementById("p1").style. = "red";// Hide an elementdocument.getElementById("myDiv").style. = "none";
DOM Events & Event Handling
What events are, common event attributes, and the ways to attach handlers.
HTML DOM Events
Events are actions or occurrences that happen in the browser. They can be triggered by the browser (page load) or by the user (click, type, hover). JavaScript code can be executed in response to any event.
| Event | Attribute | Triggered when |
|---|---|---|
click | onclick | User clicks an element. |
load | onload | Page or image finishes loading. |
mouseover | onmouseover | Mouse moves over an element. |
submit | onsubmit | Form is submitted. |
change | onchange | Input value changes. |
Common HTML Events & Event Attributes
abort (onAbort), blur (onBlur), change (onChange), click (onClick), error (onError), focus (onFocus), load (onLoad), mouseout (onMouseOut), mouseover (onMouseOver), reset (onReset), resize (onResize), select (onSelect), submit (onSubmit), unload (onUnload).
Three Ways to Specify Event Handlers
- Inline HTML attribute —
onclick="myFunction()" - DOM property assignment —
element.onclick = handler; - addEventListener() — recommended:
element.addEventListener('click', fn);
Assigning Events Using HTML Attributes
<button onclick="displayDate()">What time is it?</button>
<p id="demo"></p>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
Assigning Events Using the HTML DOM
Assign a function reference directly to the element's event property. This keeps HTML and JavaScript cleanly separated, and the handler can be swapped or removed at runtime.
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick = displayDate;
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script> Activity — complete the code
Complete the three ways of attaching an event handler.
<!-- 1. Inline HTML attribute --><button ="myFunction()">Click</button><!-- 2. DOM property assignment (function name, no parentheses) -->document.getElementById("myBtn"). = displayDate;<!-- 3. Recommended: addEventListener -->document.getElementById("myBtn").("click", displayDate);<!-- onload fires when the page finishes --><!-- -->
The addEventListener() Method
Modern, flexible event handling with multiple handlers and clean removal.
Overview
- Attaches an event handler without overwriting existing handlers.
- Add multiple handlers to one element — even of the same event type.
- Works on any DOM object, including the
windowobject. - Keeps JavaScript separate from HTML — better readability and maintenance.
- Allows fine-grained control of event bubbling vs. capturing.
- Handlers can be removed cleanly with
removeEventListener().
Syntax & Parameters
element.addEventListener(event, function, useCapture);
| Parameter | Meaning |
|---|---|
event | String — the event type, e.g. "click", "mousedown", "keyup". |
function | The callback function to call when the event fires. |
useCapture | (Optional) Boolean: true = capturing phase; false (default) = bubbling. |
Full Code Example
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
Because handlers are separate, you can also remove one later with element.removeEventListener("click", displayDate);.
Activity — complete the code
Complete the addEventListener example.
// Attach a handler without overwriting existing oneselement.("click", displayDate);// Parameters: (event, function, useCapture)element.addEventListener("keyup", myHandler, );// Remove a handler cleanlyelement.("click", displayDate);// The callback that runs when the event firesfunction () {document.getElementById("demo").innerHTML = Date();}
onLoad, Radio Buttons & JS Event Properties
Page-load handlers, reading radio button groups, and assigning handlers to JS properties.
The onLoad Event — Page Load Handler
Triggered when the loading of a document is fully completed. Ideal for running initialisation code after the page is ready.
<html>
<head>
<script>
function load_greeting() {
alert("Welcome to Pete's Pickled Peppers!");
}
</script>
</head>
<body onload="load_greeting()">
<!-- The greeting fires as soon as the page finishes loading -->
</body>
</html>
Event Handling — Radio Buttons
- All radio buttons in a group share the same
nameattribute. - You cannot identify the selected button by name — use the
checkedproperty. - Iterate over the form's
elementsarray to find the checked radio button.
var radioElements = document.myForm.elements;
var selected = "";
for (var i = 0; i < radioElements.length; i++) {
if (radioElements[i].checked) {
selected = radioElements[i].value;
break;
}
}
Assigning Event Handlers to JavaScript Properties
- Property names are lowercase versions of the HTML event attributes.
- Assign the function name (not a call) to the property.
- The handler can be replaced or removed at runtime.
- Limitation: no way to pass parameters to the handler function.
// Assign a handler to the first form element
document.myForm.elements[0].onclick = myHandler;
// For a radio button group — assign to each element
var els = document.myForm.elements;
for (var i = 0; i < els.length; i++) {
els[i].onclick = myHandler;
} Activity — complete the code
Complete the page-load handler and radio button loop.
<!-- Fires when the document has fully loaded --><body ="load_greeting()"><!-- Radio buttons share a name; use the checked property -->var els = document.myForm.;for (var i = 0; i < els.length; i++) {if (els[i].) {selected = els[i].value;break;}}// Assign a handler to a JS property (no parentheses)document.myForm.elements[0]. = myHandler;
Form Validation with Events
Checking input before submission using focus(), select() and return false.
Checking Form Input with JavaScript
JavaScript validation catches errors before data is sent to the server.
Steps for form validation
- Detect the error and display an alert message.
- Put the invalid element in focus using
focus(). - Highlight the text using
select(). return falseto prevent form submission.
// Put focus on the phone field
document.getElementById("phone").focus();
// Highlight / select the field text
document.getElementById("phone").select();
Example: Comparing Passwords
Ask the user to enter their password twice and verify they match. The handler is triggered by the form's onsubmit event.
function validatePasswords() {
var p1 = document.getElementById("pass1").value;
var p2 = document.getElementById("pass2").value;
if (p1 === "") {
document.getElementById("pass1").focus();
return false;
}
if (p1 !== p2) {
document.getElementById("pass1").focus();
document.getElementById("pass1").select();
alert("Passwords do not match!");
return false;
}
return true;
}
<form onsubmit="return validatePasswords();">
Password: <input type="password" id="pass1"><br>
Confirm: <input type="password" id="pass2"><br>
<input type="submit" value="Submit">
</form> Activity — complete the code
Complete the password validation function.
function validate() {var p1 = document.getElementById("pass1").;var p2 = document.getElementById("pass2").value;if (p1 !== p2) {document.getElementById("pass1").(); // put focus on the fielddocument.getElementById("pass1").(); // highlight the textalert("Passwords do not match!");return ; // prevent submission}return true;}
Browser Object Model (BOM)
JavaScript access to browser-level functionality via window, location, navigator, screen and history.
JavaScript Browser Object Model (BOM)
- There is no official W3C standard for the BOM — modern browsers follow a de-facto standard.
- The BOM provides objects that expose the web browser's functionality.
- The most important BOM object is the
windowobject.
| Object | Purpose |
|---|---|
window | Represents the browser window; all global variables and functions are its properties. |
location | Current page URL; enables redirect and reload. |
navigator | Information about the user's browser and operating system. |
screen | Screen dimensions and colour depth. |
history | Navigate backward/forward through the user's browsing history. |
Common BOM Code Examples
// 1. Open a new browser window
window.open('https://example.com', 'blank');
// 2. Navigate to a different URL
window.location.href = 'https://example.com';
// 3. Display an alert dialog
window.alert('Hello from BOM!');
// 4. Get screen dimensions
var w = screen.width;
var h = screen.height;
// 5. Navigate browser history
history.back(); // go back
history.forward(); // go forward
// 6. Get browser information
var browser = navigator.userAgent;
Lecture 6 Summary
- The DOM is a W3C standard programming interface for HTML documents.
- The HTML DOM represents the page as a hierarchical tree of nodes.
- Node types: document, element, text, attribute and comment.
- Use
getElementById,getElementsByTagName,querySelectorAlland more to find elements. - Change content via
innerHTML; change styles viaelement.style.property. - Events respond to user actions —
onclick,onload,onsubmit,onchange. addEventListener()is the modern, recommended approach.- Validate forms on the client side before server submission.
- The BOM (
window,navigator,location,screen,history) gives access to browser-level functionality.
Activity — complete the code
Complete the Browser Object Model examples.
// The most important BOM object//// Current page URLwindow..href = "https://example.com";// Browser informationvar browser = navigator.;// Screen dimensionsvar w = screen.;// Browsing historyhistory.(); // go back