Chapter 1 deck Chapter 2 deck Chapter 3 deck Chapter 4 deck Chapter 5 deck Chapter 6 deck Chapter 7 deck Chapter 8 deck Chapter 9 deck Chapter 10 deck Chapter 11 deck Chapter 12 deck Chapter 13 deck Chapter 14 deck

Chapter 6: JavaScript HTML DOM

55 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

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
Fullscreen for presentation · Print / PDF for a handout
1 / 55
Chapter 6

Chapter 6: JavaScript HTML DOM

The Document Object Model — how JavaScript finds, reads, changes and reacts to every element on a web page.

Lesson

Introduction to the DOM

What the Document Object Model is and the W3C DOM standard.

Introduction to the DOM

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 document object, representing the entire page.
  • It is accessible and manipulable using programming languages such as JavaScript.
Introduction to the DOM

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.”

PartPurpose
Core DOMStandard model for all document types.
XML DOMStandard model for XML documents.
HTML DOMStandard model for HTML documents.
Introduction to the DOM

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 element
var x = document.("intro");
 
// 2. Change its content
x. = "The DOM is a programming interface.";
 
// 3. Change its style
x.style. = "red";
</script>
</body>
</html>

Lesson

The HTML DOM: Objects, Properties & Methods

The HTML DOM object model, its hierarchy, and the properties/methods programming interface.

The HTML DOM: Objects, Properties & Methods

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: Objects, Properties & Methods

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.

The HTML DOM: Objects, Properties & Methods

HTML DOM Objects — Core Reference

ObjectRepresents
DocumentThe entire HTML document
EventMouse clicks, key presses
Form & Form InputForm elements
AnchorHyperlinks (<a>)
Frame / Frameset / IFrameFrames
Additional objectRepresents
ImageHTML <img> elements
LocationCurrent page URL
NavigatorBrowser information
Option & SelectDrop-down lists
ScreenScreen size and resolution
Table / TableRow / TableDataTable structures
WindowBrowser window / frame
The HTML DOM: Objects, Properties & Methods

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 ─┘
The HTML DOM: Objects, Properties & Methods

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 example
document.getElementById("demo").style. = "25px";

Lesson

DOM Tree, Nodes & Relationships

The document node tree, node types, and parent/child/sibling relationships.

DOM Tree, Nodes & 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"
DOM Tree, Nodes & Relationships

W3C HTML DOM Node Types

Node typeMeaning
Document nodeThe entire HTML document (the root).
Element nodeEvery HTML element (<p>, <div>, <span>...).
Text nodeThe text content inside HTML elements.
Attribute nodeEvery HTML attribute (id, class, href...).
Comment nodeAll HTML comments.
DOM Tree, Nodes & Relationships

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.
DOM Tree, Nodes & Relationships

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> -->

Lesson

Finding & Accessing HTML Elements

getElementById, getElementsByTagName, getElementsByClassName, querySelectorAll and form collections.

Finding & Accessing HTML Elements

The Document Object: Finding HTML Elements

To access any element, always start with the document object.

MethodDescription
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].valueAccess HTML form object collections.
Finding & Accessing HTML Elements

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 & Accessing HTML Elements

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 & Accessing HTML Elements

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 & Accessing HTML Elements

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 & Accessing HTML Elements

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>
Finding & Accessing HTML Elements

Activity — complete the code

Complete the four ways of finding elements.

// By id
var x = document.("intro");
 
// By tag name (returns a collection)
var y = document.("p");
document.write(y[0].innerHTML);
 
// By class name
var z = document.("intro");
 
// By CSS selector (returns a NodeList)
var w = document.(".intro");

Lesson

Changing HTML Content & CSS Styles

document.write(), the innerHTML property, and changing styles via the DOM.

Changing HTML Content & CSS Styles

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 & CSS Styles

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 HTML Content & CSS Styles

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";
Changing HTML Content & CSS Styles

Activity — complete the code

Complete the content and style changes.

// Write into the output stream during page load
document.("<h1>Hello!</h1>");
 
// Replace an element content
document.getElementById("demo"). = "New text!";
 
// Change a CSS style
document.getElementById("p1").style. = "red";
 
// Hide an element
document.getElementById("myDiv").style. = "none";

Lesson

DOM Events & Event Handling

What events are, common event attributes, and the ways to attach handlers.

DOM Events & Event Handling

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.

EventAttributeTriggered when
clickonclickUser clicks an element.
loadonloadPage or image finishes loading.
mouseoveronmouseoverMouse moves over an element.
submitonsubmitForm is submitted.
changeonchangeInput value changes.
DOM Events & Event Handling

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).

DOM Events & Event Handling

Three Ways to Specify Event Handlers

  1. Inline HTML attribute — onclick="myFunction()"
  2. DOM property assignment — element.onclick = handler;
  3. addEventListener() — recommended: element.addEventListener('click', fn);
DOM Events & Event Handling

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>
DOM Events & Event Handling

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>
DOM Events & Event Handling

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 -->
<!-- -->

Lesson

The addEventListener() Method

Modern, flexible event handling with multiple handlers and clean removal.

The addEventListener() Method

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 window object.
  • 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().
The addEventListener() Method

Syntax & Parameters

element.addEventListener(event, function, useCapture);
ParameterMeaning
eventString — the event type, e.g. "click", "mousedown", "keyup".
functionThe callback function to call when the event fires.
useCapture(Optional) Boolean: true = capturing phase; false (default) = bubbling.
The addEventListener() Method

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);.

The addEventListener() Method

Activity — complete the code

Complete the addEventListener example.

// Attach a handler without overwriting existing ones
element.("click", displayDate);
 
// Parameters: (event, function, useCapture)
element.addEventListener("keyup", myHandler, );
 
// Remove a handler cleanly
element.("click", displayDate);
 
// The callback that runs when the event fires
function () {
document.getElementById("demo").innerHTML = Date();
}

Lesson

onLoad, Radio Buttons & JS Event Properties

Page-load handlers, reading radio button groups, and assigning handlers to JS properties.

onLoad, Radio Buttons & JS Event 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>
onLoad, Radio Buttons & JS Event Properties

Event Handling — Radio Buttons

  • All radio buttons in a group share the same name attribute.
  • You cannot identify the selected button by name — use the checked property.
  • Iterate over the form's elements array 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;
  }
}
onLoad, Radio Buttons & JS Event Properties

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;
}
onLoad, Radio Buttons & JS Event Properties

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;

Lesson

Form Validation with Events

Checking input before submission using focus(), select() and return false.

Form Validation with Events

Checking Form Input with JavaScript

JavaScript validation catches errors before data is sent to the server.

Steps for form validation

  1. Detect the error and display an alert message.
  2. Put the invalid element in focus using focus().
  3. Highlight the text using select().
  4. return false to prevent form submission.
// Put focus on the phone field
document.getElementById("phone").focus();

// Highlight / select the field text
document.getElementById("phone").select();
Form Validation with Events

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>
Form Validation with Events

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 field
document.getElementById("pass1").(); // highlight the text
alert("Passwords do not match!");
return ; // prevent submission
}
return true;
}

Lesson

Browser Object Model (BOM)

JavaScript access to browser-level functionality via window, location, navigator, screen and history.

Browser Object Model (BOM)

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 window object.
ObjectPurpose
windowRepresents the browser window; all global variables and functions are its properties.
locationCurrent page URL; enables redirect and reload.
navigatorInformation about the user's browser and operating system.
screenScreen dimensions and colour depth.
historyNavigate backward/forward through the user's browsing history.
Browser Object Model (BOM)

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;
Browser Object Model (BOM)

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, querySelectorAll and more to find elements.
  • Change content via innerHTML; change styles via element.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.
Browser Object Model (BOM)

Activity — complete the code

Complete the Browser Object Model examples.

// The most important BOM object
//
 
// Current page URL
window..href = "https://example.com";
 
// Browser information
var browser = navigator.;
 
// Screen dimensions
var w = screen.;
 
// Browsing history
history.(); // go back