Understanding The DOM
Understanding The DOM
International License.
ISBN 978-0-9997730-9-3
Understanding the DOM — Document
Object Model
Tania Rascia
2020-10
Understanding the DOM — Document
Object Model
1. About DigitalOcean
2. Introduction
3. Introduction to the DOM
4. Understanding the DOM Tree and Nodes
5. How To Access Elements in the DOM
6. How To Traverse the DOM
7. How To Make Changes to the DOM
8. How To Modify Attributes, Classes, and Styles in the DOM
9. Understanding Events in JavaScript
About DigitalOcean
Prerequisites
In order to effectively understand the DOM and how it relates to working
with the web, it is necessary to have an existing knowledge of HTML and
CSS. It is also beneficial to have familiarity with fundamental JavaScript
syntax and code structure.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Learning the DOM</title>
</head>
<body>
<h1>Document Object Model</h1>
</body>
</html>
This code is the familiar HTML source of a new website skeleton. It
contains the absolute most essential aspects of a website document — a
doctype, and an html tag with the head and body nested inside.
For our purposes, we’ll be using the Chrome browser, but you can
receive similar output from other modern browser. Within Chrome, open
up index.html. You’ll see a plain website with our heading saying
“Document Object Model”. Right click anywhere on the page and select
“Inspect”. This will open up Developer Tools.
Under the Elements tab, you’ll see the DOM.
DOM Example
In this case, when expanded, it looks exactly the same as the HTML
source code we just wrote — a doctype, and the few other HTML tags that
we added. Hovering over each element will highlight the respective
element in the rendered website. Little arrows to the left of the HTML
elements allow you to toggle the view of nested elements.
#document
<!DOCTYPE html>
<html lang="en">
<head>
<title>Learning the DOM</title>
</head>
<body>
<h1>Document Object Model</h1>
</body>
</html>
Output
<body>
<h1>Document Object Model</h1>
</body>
Output
Conclusion
In this tutorial, we defined the DOM, accessed the document object,
used JavaScript and the console to update a property of the document
object, and went over the difference between HTML source code and the
DOM.
For more in-depth information on the DOM, review the Document
Object Model (DOM) page on the Mozilla Developer Network.
In the next tutorial, we will review important HTML terminology, learn
about the DOM tree, discover what nodes are, learn about the most
common types of nodes, and begin creating interactive scripts with
JavaScript.
Understanding the DOM Tree and Nodes
HTML Terminology
Understanding HTML and JavaScript terminology is essential to
understanding how to work with the DOM. Let’s briefly review some
HTML terminology.
To begin, let’s take a look at this HTML element.
<a href="index.html">Home</a>
a is the tag
href is the attribute
index.html is the attribute value
Home is the text.
Everything between the opening and closing tag combined make the
entire HTML element.
We’ll be working with the index.html from the previous tutorial:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Learning the DOM</title>
</head>
<body>
<h1>Document Object Model</h1>
</body>
</html>
...
<body>
<h1>Document Object Model</h1>
<^><a id="nav" href="index.html">Home</a><^>
</body>
...
Load or reload the page in your browser window and look at the DOM
to ensure that the code has been updated.
We’re going to use the getElementById() method to access the
entire element. In the console, type the following:
document.getElementById('nav');
Output
Output
<a id="nav"
href="https://www.wikipedia.org/">Navigate to
Wikipedia</a>
Refreshing the page will revert everything back to their original values.
At this point, you should understand how to use a document method to
access an element, how to assign an element to a variable, and how to
modify properties and values in the element.
Element nodes
Text nodes
Comment nodes
When an HTML element is an item in the DOM, it is referred to as an
element node. Any lone text outside of an element is a text node, and an
HTML comment is a comment node. In addition to these three node types,
the document itself is a document node, which is the root of all other
nodes.
The DOM consists of a tree structure of nested nodes, which is often
referred to as the DOM tree. You may be familiar with an ancestral family
tree, which consists of parents, children, and siblings. The nodes in the
DOM are also referred to as parents, children, and siblings, depending on
their relation to other nodes.
To demonstrate, create a nodes.html file. We’ll add text, comment,
and element nodes.
nodes.html
<!DOCTYPE html>
<html>
<head>
<title>Learning About Nodes</title>
</head>
<body>
<h1>An element node</h1>
<!-- a comment node -->
A text node.
</body>
</html>
The html element node is the parent node. head and body are
siblings, children of html. body contains three child nodes, which are all
siblings — the type of node does not change the level at which it is nested.
Note: When working with an HTML-generated DOM, the indentation of
the HTML source code will create many empty text nodes, which won’t be
visible from the DevTools Elements tab. Read about Whitespace in the
DOM
N T V E
In the Elements tab of Developer Tools, you may notice that whenever
you click on and highlight any line in the DOM the value of == $0 will
appear next to it. This is a very handy way to access the currently active
element in Developer Tools by typing $0.
In the console of nodes.html, click on the first element in the body,
which is an h1 element.
DOM Node Type
In the console, get the node type of the currently selected node with the
nodeType property.
$0.nodeType;
Output
With the h1 element selected, you would see 1 as the output, which we
can see correlates to ELEMENT_NODE. Do the same for the text and the
comment, and they will output 3 and 8 respectively.
When you know how to access an element, you can see the node type
without highlighting the element in the DOM.
document.body.nodeType;
Output
<!DOCTYPE html>
<html lang="en">
<head>
<title>Learning the DOM</title>
</head>
<body>
<h1>Document Object Model</h1>
<button id="changeBackground">Change
Background Color</button>
<script src="scripts.js"></script>
</body>
</html>
An event in JavaScript is an action the user has taken. When the user
hovers their mouse over an element, or clicks on an element, or presses a
specific key on the keyboard, these are all types of events. In this
particular case, we want our button to listen and be ready to perform an
action when the user clicks on it. We can do this by adding an event
listener to our button.
Create scripts.js and save it in the new js directory. Within the
file, we’ll first find the button element and assign it to a variable.
js/scripts.js
let button =
document.getElementById('changeBackground');
js/scripts.js
...
button.addEventListener('click', () => {
// action will go here
});
Finally, inside of the function, we will write the same code from the
previous tutorial to change the background color to fuchsia.
js/scripts.js
...
document.body.style.backgroundColor = 'fuchsia';
Here is our entire script:
js/scripts.js
let button =
document.getElementById('changeBackground');
button.addEventListener('click', () => {
document.body.style.backgroundColor = 'fuchsia';
});
Once you save this file, refresh index.html in the browser. Click the
button, and the event will fire.
Modify Background with Events
The background color of the page has changed to fuchsia due to the
JavaScript event.
Conclusion
In this tutorial, we reviewed terminology that will allow us to understand
and modify the DOM. We learned how the DOM is structured as a tree of
nodes that will usually be HTML elements, text, or comments, and we
created a script that would allow a user to modify a website without
having to manually type code into the developer console.
How To Access Elements in the DOM
Overview
Here is a table overview of the five methods we will cover in this tutorial.
G S S M
ID #demo getElementById()
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
<style>
html { font-family: sans-serif; color: #333; }
body { max-width: 500px; margin: 0 auto;
padding: 0 15px; }
div, article { padding: 10px; margin: 5px;
border: 1px solid #dedede; }
</style>
</head>
<body>
<h2>ID (#demo)</h2>
<div id="demo">Access me by ID</div>
<h2>Class (.demo)</h2>
<div class="demo">Access me by class (1)</div>
<div class="demo">Access me by class (2)</div>
<h2>Tag (article)</h2>
<article>Access me by tag (1)</article>
<article>Access me by tag (2)</article>
<h2>Query Selector</h2>
<div id="demo-query">Access me by query</div>
</body>
</html>
In this HTML file, we have many elements that we will access with
different document methods. When we render the file in a browser, it
will look similar to this:
Browser rendering of access.html page
Accessing Elements by ID
The easiest way to access a single element in the DOM is by its unique ID.
We can grab an element by ID with the getElementById() method of
the document object.
document.getElementById();
In the Console, let’s get the element and assign it to the demoId
variable.
const demoId = document.getElementById('demo');
Logging demoId to the console will return our entire HTML element.
console.log(demoId);
Output
document.getElementsByClassName();
Now we want to access more than one element, and in our example we
have two elements with a demo class.
Let’s access our elements in the Console and put them in a variable
called demoClass.
const demoClass =
document.getElementsByClassName('demo');
At this point, you might think you can modify the elements the same
way you did with the ID example. However, if we try to run the following
code and change the border property of the class demo elements to
orange, we will get an error.
demoClass.style.border = '1px solid orange';
Output
The reason this doesn’t work is because instead of just getting one
element, we have an array-like object of elements.
console.log(demoClass);
Output
document.getElementsByTagName();
Query Selectors
If you have any experience with the jQuery API, you may be familiar with
jQuery’s method of accessing the DOM with CSS selectors.
The selector for an id attribute is the hash symbol (#). We can assign
the element with the demo-query id to the demoQuery variable.
const demoQuery = document.querySelector('#demo-
query');
In the case of a selector with multiple elements, such as a class or a tag,
querySelector() will return the first element that matches the query.
We can use the querySelectorAll() method to collect all the
elements that match a specific query.
In our example file, we have two elements with the demo-query-all
class applied to them.
The selector for a class attribute is a period or full stop (.), so we can
access the class with .demo-query-all.
const demoQueryAll =
document.querySelectorAll('.demo-query-all');
Using the forEach() method, we can apply the color green to the
border property of all matching elements.
demoQueryAll.forEach(query => {
query.style.border = '1px solid green';
});
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
<style>
html { font-family: sans-serif; color: #333; }
body { max-width: 500px; margin: 0 auto;
padding: 0 15px; }
div, article { padding: 10px; margin: 5px;
border: 1px solid #dedede; }
</style>
</head>
<body>
<h2>ID (#demo)</h2>
<div id="demo">Access me by ID</div>
<h2>Class (.demo)</h2>
<div class="demo">Access me by class (1)</div>
<div class="demo">Access me by class (2)</div>
<h2>Tag (article)</h2>
<article>Access me by tag (1)</article>
<article>Access me by tag (2)</article>
<h2>Query Selector</h2>
<div id="demo-query">Access me by query</div>
<script src="access.js"></script>
</body>
</html>
Setup
To begin, we will create a new file called nodes.html comprised of the
following code.
nodes.html
<!DOCTYPE html>
<html>
<head>
<title>Learning About Nodes</title>
<style>
* { border: 2px solid #dedede; padding: 15px;
margin: 15px; }
html { margin: 0; padding: 0; }
body { max-width: 600px; font-family: sans-
serif; color: #333; }
</style>
</head>
<body>
<h1>Shark World</h1>
<p>The world's leading source on
<strong>shark</strong> related information.</p>
<h2>Types of Sharks</h2>
<ul>
<li>Hammerhead</li>
<li>Tiger</li>
<li>Great White</li>
</ul>
</body>
<script>
const h1 = document.getElementsByTagName('h1')
[0];
const p = document.getElementsByTagName('p')[0];
const ul = document.getElementsByTagName('ul')
[0];
</script>
</html>
When we load the file in a web browser, we’ll see rendering that looks
like the following screenshot.
nodes.html page
Root Nodes
The document object is the root of every node in the DOM. This object
is actually a property of the window object, which is the global, top-level
object representing a tab in the browser. The window object has access to
such information as the toolbar, height and width of the window, prompts,
and alerts. The document consists of what is inside of the inner
window.
Below is a chart consisting of the root elements that every document
will contain. Even if a blank HTML file is loaded into a browser, these
three nodes will be added and parsed into the DOM.
P N N T
Since the html, head, and body elements are so common, they have
their own properties on the document.
Open the Console in DevTools and test each of these four properties by
submitting them and viewing the output. You can also test h1, p, and ul
which will return the elements due to the variables we added in the
script tag.
Parent Nodes
The nodes in the DOM are referred to as parents, children, and siblings,
depending on their relation to other 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.
P G
We can test what the parent of our p element is with the parentNode
property. This p variable comes from our custom
document.getElementsByTagName('p')[0] declaration.
p.parentNode;
Output
► <body>...</body>
The parent of p is body, but how can we get the grandparent, which is
two levels above? We can do so by chaining properties together.
p.parentNode.parentNode;
Output
► <html>...</html>
Using parentNode twice, we retrieved the grandparent of p.
There are properties to retrieve the parent of a node, but only one small
difference between them, as demonstrated in this snippet below.
// Assign html object to html variable
const html = document.documentElement;
Children Nodes
The children of a node are the nodes that are one level below it. Any nodes
beyond one level of nesting are usually referred to as descendants.
P G
Output
In addition to the three li elements, it also gets four text nodes. This is
because we wrote our own HTML (it was not generated by JavaScript) and
the indentation between elements is counted in the DOM as text nodes.
This is not intuitive, as the Elements tab of DevTools strips out white
space nodes.
If we attempted to change the background color of the first child node
using the firstChild property, it would fail because the first node is
text.
ul.firstChild.style.background = 'yellow';
[secondary_label Output]
Uncaught TypeError: Cannot set property
'background' of undefined
The children, firstElementChild and lastElementChild
properties exist in these types of situations to retrieve only the element
nodes. ul.children will only return the three li elements.
Using firstElementChild, we can change the background color of
the first li in the ul.
ul.firstElementChild.style.background = 'yellow';
When you run the code above, your webpage will be updated to modify
the background color.
firstElementChild.style.background modification
Since our p element has both text and elements inside of it, the
childNodes property is helpful for accessing that information.
for (let element of p.childNodes) {
console.log(element);
}
Output
childNodes and children do not return arrays with all the Array
properties and methods, but they appear and behave similarly to
JavaScript arrays. You can access nodes by index number, or find their
length property.
document.body.children[3].lastElementChild.style.b
ackground = 'fuchsia';
The above code will find the last element child (li) of the fourth child
element (ul) of body and apply a style.
last child element modification
Using parent and child properties, you can retrieve any node in the
DOM.
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.
P G
Sibling properties work the same way as the 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.
In our nodes.html example, let’s select the middle element of ul.
const tiger = ul.children[1];
Since we created our DOM from scratch and not as a JavaScript web
app, we will need to use the element sibling properties to access the
previous and next element nodes, as there is white space in the DOM.
tiger.nextElementSibling.style.background =
'coral';
tiger.previousElementSibling.style.background =
'aquamarine';
Running this code should have applied coral to the background of
Hammerhead and aquamarine to the background of Great White.
sibling element modification
Sibling properties can be chained together, just like parent and node
properties.
Conclusion
In this tutorial, we covered how to access the root nodes of every HTML
document and how to walk the DOM tree through parent, child, and sibling
properties.
With what you learned in How to Access Elements in the DOM and this
tutorial, you should be able to confidently access any node in the DOM of
any website.
How To Make Changes to the DOM
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Learning the DOM</title>
</head>
<body>
<h1>Document Object Model</h1>
</body>
</html>
Right click anywhere on the page and select “Inspect” to open up
Developer Tools, then navigate to the Console.
We will use createElement() on the document object to create a
new p element.
const paragraph = document.createElement('p');
We’ve created a new p element, which we can test out in the Console.
console.log(paragraph)
Output
<p></p>
Output
Output
With these methods, we’ve created new elements and text nodes, but
they are not visible on the front end of a website until they’ve been
inserted into the document.
sibling node
todo.html
<ul>
<li>Buy groceries</li>
<li>Feed the cat</li>
<li>Do laundry</li>
</ul>
When you load your page in the browser, it will look like this:
DOM Screenshot 1
In order to add a new item to the end of the to-do list, we have to create
the element and add text to it first, as we did in the “Creating New Nodes”
section above.
// To-do list ul element
const todoList = document.querySelector('ul');
todo.html
<ul>
<li>Buy groceries</li>
<li>Feed the cat</li>
<li>Do laundry</li>
<li>Do homework</li>
</ul>
DOM Screenshot 2
Maybe we have a higher priority task to do, and we want to add it to the
beginning of the list. We’ll have to create another element, as
createElement() only creates one element and cannot be reused.
// Create new to-do
const anotherTodo = document.createElement('li');
anotherTodo.textContent = 'Pay bills';
We can add it to the beginning of the list using insertBefore().
This method takes two arguments — the first is the new child node to be
added, and the second is the sibling node that will immediately follow the
new node. In other words, you’re inserting the new node before the next
sibling node. This will look similar to the following pseudocode:
parentNode.insertBefore(newNode, nextSibling);
For our to-do list example, we’ll add the new anotherTodo element
before the first element child of the list, which is currently the Buy
groceries list item.
// Add new to-do to the beginning of the list
todoList.insertBefore(anotherTodo,
todoList.firstElementChild);
todo.html
<ul>
<li>Pay bills</li>
<li>Buy groceries</li>
<li>Feed the cat</li>
<li>Do laundry</li>
<li>Do homework</li>
</ul>
DOM Screenshot 3
The new node has successfully been added at the beginning of the list.
Now we know how to add a node to a parent element. The next thing we
may want to do is replace an existing node with a new node.
We’ll modify an existing to-do to demonstrate how to replace a node.
The first step of creating a new element remains the same.
const modifiedTodo = document.createElement('li');
modifiedTodo.textContent = 'Feed the dog';
Like insertBefore(), replaceChild() takes two arguments —
the new node, and the node to be replaced, as shown in the pseudocode
below.
parentNode.replaceChild(newNode, oldNode);
We will replace the third element child of the list with the modified to-
do.
// Replace existing to-do with modified to-do
todoList.replaceChild(modifiedTodo,
todoList.children[2]);
todo.html
<ul>
<li>Pay bills</li>
<li>Buy groceries</li>
<li>Feed the dog</li>
<li>Do laundry</li>
<li>Do homework</li>
</ul>
DOM Screenshot 4
Using the to-do example above, we’ll want to delete items after they’ve
been completed. If you completed your homework, you can remove the Do
homework item, which happens to be the last child of the list, with
removeChild().
todoList.removeChild(todoList.lastElementChild);
todo.html
<ul>
<li>Pay bills</li>
<li>Buy groceries</li>
<li>Feed the dog</li>
<li>Do laundry</li>
</ul>
DOM Screenshot 5
todo.html
<ul>
<li>Pay bills</li>
<li>Feed the dog</li>
<li>Do laundry</li>
</ul>
DOM Screenshot 6
Conclusion
In this tutorial, we learned how to use JavaScript to create new nodes and
elements and insert them into the DOM, and replace and remove existing
nodes and elements.
At this point in the Understanding the DOM series you know how to
access any element in the DOM, walk through any node in the DOM, and
modify the DOM itself. You can now feel confident in creating basic front-
end web apps with JavaScript.
How To Modify Attributes, Classes, and
Styles in the DOM
Accessing a single element, we can easily update a part of the element such
as the text inside.
Modifying Attributes
Attributes are values that contain additional information about HTML
elements. They usually come in name/value pairs, and may be essential
depending on the element.
Some of the most common HTML attributes are the src attribute of an
img tag, the href of an a tag, class, id, and style. For a full list of
HTML attributes, view the attribute list on the Mozilla Developer Network.
Custom elements that are not part of the HTML standard will be prepended
with data-.
In JavaScript, we have four methods for modifying element attributes:
M D E
boolean
an element
Let’s create a new HTML file with an img tag with one attribute. We’ll link
to a public image available via a URL, but you can swap it out for an alternate
local image if you’re working offline.
attributes.html
<!DOCTYPE html>
<html lang="en">
<body>
<img src="https://js-
tutorials.nyc3.digitaloceanspaces.com/shark.png">
</body>
</html>
When you load the above HTML file into a modern web browser and open
the built-in Developer Console, you should see something like this:
First rendering of classes.html
img.hasAttribute('src'); // returns
true
img.getAttribute('src'); // returns
"...shark.png"
img.removeAttribute('src'); // remove the
src attribute and value
At this point, you will have removed the src attribute and value associated
with img, but you can reset that attribute and assign the value to an alternate
image with img.setAttribute():
img.setAttribute('src', 'https://js-
tutorials.nyc3.digitaloceanspaces.com/octopus.png');
Finally, we can modify the attribute directly by assigning a new value to the
attribute as a property of the element, setting the src back to the
shark.png file
img.src = 'https://js-
tutorials.nyc3.digitaloceanspaces.com/shark.png';
Any attribute can be edited this way as well as with the above methods.
The hasAttribute() and getAttribute() methods are usually
used with conditional statements, and the setAttribute() and
removeAttribute() methods are used to directly modify the DOM.
Modifying Classes
The class attribute corresponds to CSS class selectors. This is not to be
confused with ES6 classes, a special type of JavaScript function.
CSS classes are used to apply styles to multiple elements, unlike IDs which
can only exist once per page. In JavaScript, we have the className and
classList properties to work with the class attribute.
M /P D E
class value
more class
values
on or off
value exists
value with a
value
We’ll make another HTML file to work with the class methods, with two
elements and a few classes.
classes.html
<!DOCTYPE html>
<html lang="en">
<style>
body {
max-width: 600px;
margin: 0 auto;
font-family: sans-serif;
}
.active {
border: 2px solid blue;
}
.warning {
border: 2px solid red;
}
.hidden {
display: none;
}
div {
border: 2px dashed lightgray;
padding: 15px;
margin: 5px;
}
</style>
<body>
<div>Div 1</div>
<div class="active">Div 2</div>
</body>
</html>
When you open the classes.html file into a web browser, you should
receive a rendering that looks similar to the following:
activeDiv.classList.add('hidden'); //
Add the hidden class
activeDiv.classList.remove('hidden'); //
Remove the hidden class
activeDiv.classList.toggle('hidden'); //
Switch between hidden true and false
activeDiv.classList.replace('active', 'warning'); //
Replace active class with warning class
After performing the above methods, your web page will look like this:
Final rendering of classes.html
Modifying Styles
The style property repesents the inline styles on an HTML element. Often,
styles will be applied to elements via a stylesheet as we have done previously
in this article, but sometimes we have to add or edit an inline style directly.
We will make a short example to demonstrate editing styles with
JavaScript. Below is a new HTML file with a div that has some inline styles
applied to display a square.
styles.html
<!DOCTYPE html>
<html lang="en">
<body>
</body>
</html>
// Select div
const div = document.querySelector('div');
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
div.style.height = '100px';
div.style.width = '100px';
div.style.border = '2px solid black';
Conclusion
HTML elements often have additional information assigned to them in the
form of attributes. Attributes may consist of name/value pairs, and a few of
the most common attributes are class and style.
In this tutorial, we learned how to access, modify, and remove attributes on
an HTML element in the DOM using plain JavaScript. We also learned how to
add, remove, toggle, and replace CSS classes on an element, and how to edit
inline CSS styles. For additional reading, check out the documentation on
attributes on the Mozilla Developer Network.
Understanding Events in JavaScript
To begin learning about event handlers, we’ll first consider the inline
event handler. Let’s start with a very basic example that consists of a
button element and a p element. We want the user to click the button
to change the text content of the p.
Let’s begin with an HTML page with a button in the body. We’ll be
referencing a JavaScript file that we’ll add code to in a bit.
events.html
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Events</title>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Events</title>
</head>
<body>
<button onclick="changeText()">Click
me</button>
</body>
<script src="js/events.js"></script>
</html>
Let’s create our events.js file, which we placed in the js/ directory
here. Within it, we will create the changeText() function, which will
modify the textContent of the p element.
js/events.js
When you first load the events.html, you’ll see a page that looks
like this:
events.html
...
<body>
<button>Click me</button>
</body>
...
Our function will remain similar as well, except now we need to access
the button element in the JavaScript. We can simply access onclick
just as we would access style or id or any other element property, then
assign the function reference.
js/events.js
Note: Event handlers do not follow the camelCase convention that most
JavaScript code adheres to. Notice that the code is onclick, not
onClick.
When you first load the page, the browser will display the following:
Initial load of events.html with events handler
Now when you click the button, it will have a similar effect as before:
js/events.js
const p = document.querySelector('p');
const button = document.querySelector('button');
In the above example, the button click would only display an alert,
and not change the p text, since the alert() code was the last one added
to the property.
Final response via events handler of events.html
Event Listeners
...
<button>Click me</button>
js/events.js
const p = document.querySelector('p');
const button = document.querySelector('button');
In this example, both events will fire, providing the user with both an
alert and modified text once clicking out of the alert.
Often, anonymous functions will be used instead of a function reference
on an event listener. Anonymous functions are functions that are not
named.
// An anonymous function on an event listener
button.addEventListener('click', () => {
p.textContent = "Will I change?";
});
Common Events
We have learned about inline event handlers, event handler properties, and
event listeners using the click event, but there are many more events in
JavaScript. We will go over a few of the most common events below.
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.
E D
Form Events
Form events are actions that pertain to forms, such as input elements
being selected or unselected, and forms being submitted.
E D
Keyboard Events
Keyboard events are used for handling keyboard actions, such as pressing
a key, lifting a key, and holding down a key.
E D
Once we press ENTER on the Console, we can now press a key on the
keyboard, in this example, we’ll press a.
Output
keyCode: 65
key: a
code: KeyA
The keyCode property is a number that pertains to the key that has
been pressed. The key property is the name of the character, which can
change — for example, pressing a with SHIFT would result in a key of
A. The code property represents the physical key on the keyboard.
Note that keyCode is in the process of being deprecated and it is
preferable to use code in new projects.
To learn more, you can view the complete list of events on the Mozilla
Developer Network.
Event Objects
The Event object consists of properties and methods that all events can
access. In addition to the generic Event object, each type of event has its
own extensions, such as KeyboardEvent and MouseEvent.
The Event object is passed through a listener function as a parameter.
It is usually written as event or e. We can access the code property of
the keydown event to replicate the keyboard controls of a PC game.
To try it out, create a basic HTML file with <p> tags and load it into a
browser.
event-test-p.html
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Events</title>
</head>
<body>
<p></p>
</body>
</html>
Then, type the following JavaScript code into your browser’s Developer
Console.
// Pass an event through to a listener
document.addEventListener('keydown', event => {
var element = document.querySelector('p');
From here, you can continue to develop how the browser will respond
and to the user pressing those keys, and can create a more dynamic
website.
Next, we’ll go over one of the most frequently used event properties:
the target property. In the following example, we have three div
elements inside one section.
event-test-div.html
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Events</title>
</head>
<body>
<section>
<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
</section>
</body>
</html>
Clicking on any one of those elements will return output of the relevant
specific element to the Console using event.target. This is extremely
useful, as it allows you to place only one event listener that can be used to
access many nested elements.
With the Event object, we can set up responses related to all events,
including generic events and more specific extensions.
Conclusion
Events are actions that take place on a website, such as clicking, hovering,
submitting a form, loading a page, or pressing a key on the keyboard.
JavaScript becomes truly interactive and dynamic when we are able to
make websites respond to actions the user has taken.
In this tutorial, we learned what events are, examples of common
events, the difference between event handlers and event listeners, and how
to access the Event object. Using this knowledge, you will be able to
begin making dynamic websites and applications.