Document Object Model
\title{ Document Object Model }
{Learning Objectives}
This lesson provides an overview of the Document Object Model (DOM) and JavaScript events. By the end of this lesson, learners will be able to:
Navigate the DOM using JavaScript selectors.
Navigate between DOM nodes using relationship properties.
Add and remove content from the DOM.
Access and change DOM element attributes.
Change style attributes of elements using JavaScript.
Use Event Handlers and Event Listeners to perform actions in response to user interaction.
{Table of Contents}
Section One: DOM Properties and Methods
The HTML Document Object Model
The Document Object Model - Nodes
Useful DOM Objects, Properties, and Methods
Locating DOM Elements using Selectors
Document Structure and Traversal
Documents as Trees of Nodes
$>\quad$ Node Relationships
$>\quad$ Making Changes to the DOM Section Two: JavaScript Events
Events in JavaScript
Event Handlers
Mouse Events
Form Events
Keyboard Events
Keyboard Events Properties
{Section 1 \ DOM Properties and Methods}
{The HTML Document Object Model}
The Document Object Model (DOM) is an interface that allows programs to dynamically access and update the content, structure, and style of a document.
DOM defines the logical structure of documents and the way a document is accessed and manipulated.
Javascript provides DOM class that defines HTML elements as objects. It support properties, methods, and events, which are available for the web developer for manipulating and creating web pages organized into objects. Those objects are accessible through modern web browsers.
In the DOM, all HTML elements are defined as objects.
{The HTML Document Object Model}
An HTML document consists of nested HTML elements. The document can be viewed as a tree of elements. Each element is a child of the element that immediately encloses it. Similarly, each element is an ancestor of all the elements it encloses.
Consider the following simple HTML document:
The DOM representation of the document.
{The Document Object Model - Nodes}
A node is a generic name for any type of object in the DOM hierarchy. A node in this context is simply an HTML element. A node could be one of the built-in DOM elements such as document or document. body, an HTML tag specified in
Each HTML element is represented by an object. Each object has various properties and methods that correspond to the appearance or behavior of the corresponding HTML element. The object also has parents, children, and siblings as specified by the DOM tree.
In this example, the element is the parent of two $\langle p\rangle$ child nodes and the ancestor to the one $\langle$ em $\rangle$ node.
{Useful DOM Objects, Properties, and Methods}
The following are some useful objects, properties, and methods of the document object:
document.anchors: Returns all $\langle\mathrm{a}\rangle$ elements that have - a name attribute.
document.baseURI: Returns the absolute base URI of the document.
document. body: Returns the 〈body $\rangle$ element. document. cookie: Returns the document's cookie. document. doctype: Returns the document's doctype.
document.documentMode: Returns the mode used by the browser.
document.documentURI: Returns the URI of the document.
document.domain: Returns the domain name of the document server.
document. embeds: Returns all <embed $\rangle$ elements.
document.strictErrorChecking: Returns if error checking is enforced.
document.title: Returns the $\langle$ title $\rangle$ element.
document.URL: Returns the complete URL of the document.
document. forms: Returns all $\langle$ form - elements.
document. head: Returns the <head $\rangle$ element.
document.implementation: Returns the DOM implementation.
document.inputEncoding: Returns the document's encoding (character set).
document.lastModified: Returns the date and time the document was updated.
document. referrer: Returns the URI of the referrer (the linking document).
{Locating DOM Elements using Selectors}
In order to manipulate elements of the document, you must somehow obtain or select the element objects that represent the page elements of interest.
The DOM defines several ways to select elements, which we will discuss on the following slides. You can query a document for an element or elements by using:
Document/HTML object collections.
A specific id attribute.
A specific name attribute.
A specific tag name.
A Cascading Style Sheet (CSS) class or classes.
A CSS selector expression.
{Selecting Elements by ID}
Any HTML element can have an id attribute, but no two elements in a document should have the same id.
You can select an element based on this unique id with the getElementById() method of the document object, which returns an element object representing the element whose id property matches the specified string.
{Selecting Elements by Name}
To select HTML elements based on the value of their name attributes, we can use the getElementsByName( ) method of the document object, which returns a collection of all elements in the document with the specified tag name as a NodeList object. NodeList objects behave like a read-only array of Element objects.
{Selecting Elements by Type}
You can select all HTML elements of a specified type (or tag name) using the getElementsByTagName () method of the document object.
,
{NodeLists and HTMLCollections}
\author{ getElementsByName () and \ getElementsByTagName ( ) return NodeList \ objects and properties such as \ document . images and document. forms in \ HTMLCollection objects. }
These objects are read-only, array-like objects. They have length properties and can be indexed (for reading but not writing) like true arrays. You can iterate the contents of a NodeList or HTMLCollection with a standard loop. You cannot invoke Array methods on NodeList and HTMLCollection directly, but you can do so indirectly.
{Selecting Elements by CSS Class}
{Selecting Elements with CSS Selectors}
The querySelector() method returns the first element that matches a specified CSS selector or multiple selectors in the document.
{Selecting Elements with CSS Selectors (continued)}
{Selecting Elements with CSS Selectors (continued)}
The document method
querySelectorAll() takes a single string argument containing a CSS selector and returns a NodeList that represents all elements in the document that match the selector.
{Document Structure and Traversal}
We know that the DOM is structured as a tree of nodes with the document node at the root and every other node (including elements, comments, and text nodes) as the various branches.
Often, you will want to move through the DOM without specifying each element beforehand. For these cases, we can navigate up and down the DOM tree and move from branch to branch with the parent, child, and sibling properties.
https://javascript.info/dom-navigation
{Documents as Trees of Nodes}
In the DOM, element objects and the text objects that represent text in the document are all Node objects. Node defines the following important properties:
Root Nodes.
Parent Nodes.
Children Nodes.
Sibling Nodes.
The nodes in the DOM are referred to as parents, children, and siblings depending on their relation to other nodes as shown in the representation to the right.
{Node Relationships - Example}
You can use the following node properties to navigate between nodes with JavaScript:
Consider the following code:
In the example code to the left:
is the root node
has no parents
$\langle$ head $\rangle$ is the first child of $\langle$ html>
〈body is the last child of $\langle$ html>
〈head〉 has one child:〈title〉
has one child (a text node): "DOM Tutorial"
$\langle\mathrm{h} 1\rangle$ has one child: "DOM Lesson one"
$\langle p\rangle$ has one child: "Hello world!"
$\langle h 1\rangle$ and $\langle\mathrm{p}\rangle$ are siblings
{Root Nodes}
The document object is the root of every node in the DOM. This object is a property of the window object, which is the global, top-level object representing a tab in the browser (more on the window object later).
Since the html, head, and body elements are so commonly used, they have their own properties in the document object: (document . documentElement, document . head, document . body respectively).
{Parent Nodes}
The parent of any node is the node that is one level above it, or closer to the document in the DOM hierarchy. There are two properties to get the parent: parentNode and parentElement.
In the example to the right:
html is the parent of head, body and script.
body is the parent of $u \mathbf{l}$, but not $\mathbf{l i}$, since $1 \mathbf{i}$ is two levels down from body.
Note: Using parentNode twice, we
{Children Nodes}
In this example, the ul element has four child li elements.
firstChild and lastChild: The first and last child nodes of a node, or null if the node has no children.
The difference between the firstChild and firstElementChild properties is that firstChild returns the first child node as an element node, a text node, or a comment node (depending on which one is first), while firstElementChild returns exclusively the first element node (ignores text and comment nodes).
{Sibling Nodes}
The siblings of a node are any node on the same tree level in the DOM. Siblings do not have to be the same type of node. Text, element, and comment nodes can all be siblings.
Sibling properties work the same way as children nodes, in that there is a set of properties to traverse all nodes, and a set of properties for only element nodes: previousSibling and nextSibling will get the next node that immediately precedes or follows the specified node, and previousElementSibling and nextElementSibling will only get element nodes.
{Making Changes to the DOM}
We have explored how to query the document using strings of HTML and plain text. We have also seen that we can traverse a document to examine the individual element and text nodes that it is made of.
It is also possible to alter a document at the level of individual nodes. The document type defines methods for creating element and text objects, and the Node type defines methods for inserting, deleting, and replacing nodes in the tree.
{The innerHTML Property}
The easiest way to access the content of an element is by using the innerHTML property. The innerHTML property is useful for getting or replacing the content of HTML elements, including $\langle h t m l\rangle$ and $\langle$ body .
It is used in web pages to generate dynamic HTML such as registration forms, comment forms, links etc.
In the example on the right, we are dynamically writing the HTML data inside the div element with the id "mylocation". We are selecting this element by calling the document getElementById () method.
{Inserting Nodes into the DOM}
With these methods, we have created new elements and text nodes, but they are not visible on the front end of a website until they have been inserted into the document.
The methods appendChild() and insertBefore () are used to add items to the beginning, middle, or end of a parent element, and replaceChild() is used to replace an old node with a new node.
{Creating New Nodes}
In a static website, elements are added to the page by directly writing HTML in an .html file. In a dynamic web app, elements and text are often added with JavaScript.
The createElement() and createTextNode() methods are used to create new nodes or elements and content in the DOM.
{Removing Nodes}
The removechild() method removes a node from the document tree.
Invoke the method on the parent node and pass the child node that is to be removed as the method argument. The remove() method removes the object from the tree it belongs to.
{Modifying Styles}
The style property represents the inline styles on an HTML element. Often, styles will be applied to elements via a stylesheet, but sometimes we must add or edit an inline style directly.
One option to edit the styles is with setAttribute( ). However, this will remove all existing inline styles from the element. Since this is likely not the intended effect, it is better to use the style attribute directly.
{Section 2 \ JavaScript Events}
{Events in JavaScript}
Events are actions that take place in the browser that can be initiated by either the user or the browser itself. Events allow JavaScript to register different event handlers on elements in an HTML document.
Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button).
By coding JavaScript responses that execute upon an event, developers can display messages to users, validate data, react to a button click, and implement many other interactions.
http://mason.gmu.edu/
{Event Handlers}
Each event may have an event handler, which is a block of code that will execute when the event occurs. There are three ways to assign events to elements:
Inline event handlers object.EventName( ) = function( $){$ myScript $} ;$
Event handler properties object.EventName $=$ methodName ();
Event listeners object.addEventListener("EventName", myScript);
{Inline Event Handlers}
Inline events are bound to an element by their attribute name, which starts with the "on" prefix. onchange is usually associated with text input fields, and a handler can be set in HTML with an attribute named on. For instance, to assign a click handler for an input tag, we can use "onclick."
It is more practical to maintain a separate stylesheet of CSS classes than to create inline styles on every element. Similarly, it is more feasible to maintain JavaScript that is handled entirely through a separate script file than to add handlers to every element.
{Event Handler Properties}
Event Handler properties work similar to inline handlers, except we set the property of an element in JavaScript instead of the attribute in the HTML.
The event handler property is slightly more maintainable than the inline handler, but it still suffers from some of the same hurdles. For example, trying to set multiple, separate "onclick" properties will cause all but the last one to be overwritten.
{Event Listeners}
An Event Listener is a function with an explicit name (if it is reusable) or an anonymous function (in case it is used one time).
When a user clicks a button or presses a key, an event is fired. These are called click events or keypress events, respectively. An event listener attaches a responsive interface to an element, which allows that element to wait and "listen" for the given event to fire.
Event Handlers provide two main methods for registering and deregistering event listeners:
addEventListener() - register an event handler.
removeEventListener() - remove an event handler.
{Event Listeners (continued)}
Event listeners are currently the most common and preferred way to handle events in JavaScript. An event listener watches for an event on an element. Instead of assigning the event directly to a property on the element, we will use the addEventListener( ) method to listen for the event.
addEventListener () takes two mandatory parameters - the event it is to be listening for, and the listener callback function.
{Mouse Events}
Mouse events are among the most frequently used events. They refer to events that involve clicking buttons on the mouse or hovering and moving the mouse pointer. These events also correspond to the equivalent action on a touch device.
\begin{tabular}{|c|l|l|} \hline Event & Event Handler & Description \ \hline click & onclick & $\begin{array}{l}\text { When mouse click on an element or fires when the mouse is } \ \text { pressed and released on an element }\end{array}$ \ \hline mouseover & onmouseover & When the cursor of the mouse comes over the element \ \hline mouseout & onmouseout & When the cursor of the mouse leaves an element \ \hline mousedown & onmousedown & When the mouse button is pressed over the element \ \hline mouseup & onmouseup & When the mouse button is released over the element \ \hline mousemove & onmousemove & $\begin{array}{l}\text { Fires every time a pointer moves inside an element or when } \ \text { the mouse movement takes place. }\end{array}$ \ \hline mouseenter & onmouseenter & Fires when a pointer enters an element \ \hline mouseleave & onmouseleave & Fires when a pointer leaves an element \ \hline \end{tabular}
A click is a compound event that is comprised of combined mousedown and mouseup events, which fire when the mouse button is pressed down or lifted, respectively.
Using mouseenter and mouseleave in tandem recreates a hover effect that lasts for as long as a mouse pointer is on the element.
{Mouse Events - Example: onclick}
{Mouse Events - Example: onmouseover}
{Form Events}
Form events are actions that pertain to forms, such as input elements being selected or unselected, and forms being submitted.
Focus is achieved when an element is selected, such as through a mouse click or navigating to it via the TAB key, and there are events tied to element focus.
JavaScript is often used to submit forms, and send the values through to a back-end language.
{Form Events (continued)}
onsubmit()
Fires when a form is submitted.
onfocus ()
Fires when an element (such as
an input) receives focus.
onblur ()
Fires when an element loses focus.
{onchange()}
Fires when the user modifies the value of a form element.
{Form Events - Example: onfocus}
{Form Events: onsubmit}
The onsubmit event is an event that occurs when you try to submit a form. You can put your form validation against this event type. The example shows how to use onsubmit.
Here we are calling a validate() function before submitting a form data to the web server. If the validate() function returns true, the form will be submitted; otherwise, it will not submit the data.
{Keyboard Events}
Keyboard events are used for handling keyboard actions such as pressing a key, lifting a key, and holding down a key.
Although they look similar, keydown and keypress events do not access all of the exact same keys. While keydown will acknowledge every key that is pressed, keypress will omit keys that do not produce a character, such as SHIFT, ALT, or DELETE.
{keydown}
Fires once when a key is pressed.
{keyup}
Fires once when a key is released.
{keypress}
Fires continuously while a key is pressed.
{Keyboard Events Properties - Example}
We can access the code property of the keydown event to replicate the keyboard controls of a PC game, as shown.
\author{ Press $\mathrm{A}, \mathrm{W}, \mathrm{D}$ or $\mathrm{S}$ \ for Up, Left, Right, or Down }
UP
LEFT RIGHT
DOWN
Source: Per Scholas
{Activity: DOM Manipulation and Event Listeners}
Create a single page with two boxes at the bottom of the page; these boxes should be styled as chat windows, as described below.
Chat windows let the user input a name and send a message. They include a recent messages area, and a submit button. Once submitted, the message, along with the name, should be displayed in both chat windows.
Do not manually create any HTML elements in your page; instead, use the document. createElement() and element . appendChild() or similar methods to add elements to your page. Your page should only consist of the html, head, and body tags before executing your script.
Do not use CSS to describe the presentation of pages; instead, use style property and the setAttribute() or similar methods to manipulate your elements styles.
The messages, along with the user name, should be displayed in the chat windows in order.
Add mouse event listeners and handlers to the submit button on each chat window.
Add keyboard event listeners and handlers to the text area on each chat window to submit the messages each time the user presses the "ENTER" key.
{Knowledge Check}
What is the DOM?
What is a Node?
What is the Root Node?
What are two common methods for selecting elements in the DOM?
What methods can be used to traverse the DOM between related nodes?
What is the purpose of the innerHTML property?
How do you insert or remove nodes from the DOM with JavaScript?
How do you modify an elements styles with JavaScript?
What is an event handler?
What is an event listener?
{Summary}
The Document Object Model (DOM) is an interface that allows programs to dynamically access and update the content, structure, and style of a document.
Objects in the DOM hierarchy are called nodes:
Nodes can be selected via methods that use attributes such as id, name, and class.
Nodes can be traversed by using their parent-child relationships and properties such as parentNode and nextSibling.
Nodes can be added or removed from the DOM via JavaScript functions such as appendNode() and removeChild(), among others.
The contents and style of nodes can also be accessed and modified using properties like innerHTML and style.
Events in JavaScript can be listened for and handled via a number of functions and properties specific to each event. Handling events allows you to create responsive, dynamic content.
{Questions?}
Last updated