JavaScript DOM
JavaScript DOM
GETTING STARTED
SELECTING ELEMENTS
Select Element By Id
Select Elements By Name
Select Elements By Tag Name
Select Elements By Class Names
Select Element By CSS Selectors
TRAVESING ELEMENTS
MANIPULATING ELEMENTS
Create Elements
Append Child Nodes
Get or Set Text of a Node
Get or Set HTML of an Element
innerHTML vs createElement
Use DocumentFragment
Insert a Node Before Another
Insert a Node After Another
Insert a Node before the first Child Node of an Element
Insert a Node after the last Child Node of an Element
insertAdjacentHTML
Replace Child Elements
Clone a Node
Remove Child Elements
MANGING ATTRIBUTES
HANDLING EVENTS
Introduction to Events
Event Handling
Page Load Events
The onload Event
The DOMContentLoaded Event
The unload Event
The beforeunload Event
Mouse Events
Keyboard Events
Scroll Events
Scroll an Element Into View
Focus Events
The haschange Event
Event Delegation
Simulate Events
Custom Events
SCRIPTING FORMS
MINI PROJECTS
HTML Attributes & DOM Object’s Properties – understand the relationship between
HTML attributes & DOM object’s properties.
setAttribute() – set the value of a specified attribute on a element.
getAttribute() – get the value of an attribute on an element.
removeAttribute() – remove an attribute from a specified element.
hasAttribute() – check if an element has a specified attribute or not.
JavaScript events – introduce you to the JavaScript events, the event models, and how to
handle events.
Handling events – show you three ways to handle events in JavaScript.
Page Load Events – learn about the page load and unload events.
load event – walk you through the steps of handling the load event originated from the
document, image, and script elements.
DOMContentLoaded – learn how to use the DOMContentLoaded event correctly.
beforeunload event – guide you on how to show a confirmation dialog before users
leave the page.
unload event – show you how to handle the unload event that fires when the page is
completely unloaded.
Mouse events – how to handle mouse events.
Keyboard events – how to deal with keyboard events.
Scroll events – how to handle scroll events effectively.
scrollIntoView – learn how to scroll an element into view.
Focus Events – cover the focus events.
haschange event – learn how to handle the event when URL hash changes.
Event Delegation – is a technique of levering event bubbling to handle events at a higher
level in the DOM than the element on which the event originated.
dispatchEvent – learn how to generate an event from code and trigger it.
Custom Events – define a custom JavaScript event and attach it to an element.
MutationObserver – monitor the DOM changes and invoke a callback when the changes
occur.
Section 8. Scripting Web Forms
JavaScript Form – learn how to handle form submit event and perform a simple validation
for a web form.
Radio Button – show you how to write the JavaScript for radio buttons.
Checkbox – guide you on how to manipulate checkbox in JavaScript.
Select box – learn how to handle the select box and its option in JavaScript.
Add / Remove Options – show you how to dynamically add options to and remove
options from a select box.
Handling change event – learn how to handle the change event of the input text, radio
button, checkbox, and select elements.
Handling input event – handle the input event when the value of the input element
changes.
JavaScript Snippets
SNIPPETS
Array5
DOM47
o Selecting5
o Traversing4
o Manipulating10
o Attributes4
o CSS15
o Events9
Object6
String3
RECENT SNIPPETS
JavaScript Snippets
DOM
This section provides you with handy functions for selecting, traversing, and
manipulating DOM elements.
Selecting
Selecting an Element By Id
Select elements that match a tag name using the getElementsByTagName() method.
Select elements that match a class name using the getElementsByClassName method.
This tutorial shows you how to select elements by name using the JavaScript
getElementsByName() method
Select elements that match a CSS selector using the querySeelctor() and querySelectorAll()
methods.
Traversing
Get the Parent of an Element
Get the parent node of an element by using the parentNode property of the element.
Clone an Element
Get or set the text content of an Element using the textContent property.
Get and set the HTML of an element using the innerHTML property.
Remove an element from the DOM tree using the removeChild() method.
Iterate over selected elements using forEach() method and plain old for loop.
Attributes
This section shows you how to manipulate the element’s attributes including getting, setting, and
removing attributes.
Check if an attribute with a specified name exists using the hasAttribute() method.
CSS
This section shows you how to manipulate the element’s CSS using JavaScript DOM methods.
This tutorial shows you how to get the scrollbar width of an element in JavaScript.
In this tutorial, you’ll learn how to check if an element is visible in the viewport using
JavaScript.
This tutorial shows you how to replace a class with a new one using JavaScript DOM API.
Check If an Element contains a Class
This tutorial shows you how to check if an element contains a specific class using JavaScript
DOM API.
This tutorial shows you how toggle a class of an element using the JavaScript DOM API.
This tutorial shows you how to remove one or more classes from an element using JavaScript
DOM API.
This tutorial shows you how to add one or more classes to an element in JavaScript
This tutorial shows you how to get the width and height of an element using JavaScript DOM
API.
To get the top/left coordinates of an element relative to its parent, you use the offsetLeft and
offsetTop properties. The return values are in px:
This tutorial shows you how to get the width and height of the window in JavaScript
This tutorial shows you how to get and set the scroll position of the document.
This tutorial shows you how to get and set the scroll position of an element using JavaScript
DOM API.
Toggle an Element
This tutorial shows you how to toggle an element using plain JavaScript DOM API
Get Styles of an Element
In this tutorial, you’ll learn how to add styles to an element using JavaScript DOM methods.
Events
This section shows you the most commonly used functions for dealing with events in the web
browsers.
This tutorial shows you how to detect if the caps lock is on using JavaScript DOM API.
This tutoial shows you how to check if the document is ready using vanilla JavaScript.
This tutorial shows you how to attach an event handler to an event of an element in JavaScript.
This tutorial shows you how to use the removeEventListener() method to remove an event
handler from an event of an element.
This tutorial shows you how to use the addEventListener() method to create a one-off event
handler that execute only once when the event occurs for the first time.
This tutorial shows you how to detect if an element has the focus.
Trigger an Event
This tutorial shows you how to trigger an event on an element programmatically using JavaScript
DOM API.
Prevent Default Action of Events
This tutorial shows you how to prevent the default action of an event by using the
preventDefault() method of the Event object.
This tutorial shows you how to stop the propagation of an event in both capturing and bubbling
phases using the Event.stopPropagation() method.
Array
How to Check if an Array Contains a Value in Javascript
In this tutorial, you’ll learn how to check if an array contains a value in JavaScript.
This tutorial shows you how to use the Array.isArray() method and instanceof operator to check
if a variable is an array in JavaScript
In this tutorial, you will learn some techniques to to remove duplicates from an array in
JavaScript.
In this tutorial, you will learn how to sort an array of objects by the values of the object’s
properties
Object
An Essential Guide to JavaScript null
In this tutorial, you’ll learn about the JavaScript null and how to handle it effectively.
3 Ways to Check If a Property Exists in an Object
In this tutorial, you will learn how to check if a property exists in an object in JavaScript.
Merge objects into a single object using the spread operator (…) or Object.assign() method.
Copy an object using spread (…) syntax, Object.assign() method, or JSON methods.
JavaScript Window
Summary: in this tutorial, you will learn about the JavaScript window object which is the
global object of JavaScript in the browser and exposes the browser ‘s functionality.
The window object is the Global object
var counter = 1;
var showCounter = () => console.log(counter);
console.log(window.counter);
window.showCounter();
Code language: JavaScript (javascript)
Output:
1
counter 1
Since the counter variable and the showCounter() function are declared globally with
the var keyword, they are automatically added to the window object. If you don’t want to
pollute the window object, you can use the let keyword to declare variables and functions.
1) Window size
Also, document.documentElement.clientWidth and document.documentElement.clientHeight properties
indicate the width and height of the page viewport. To get the size of the window, you
use the following snippet:
The window.open() method accepts three arguments: the URL to load, the window target
and a string of window features.
The code opens the page about.html in a new tab. If you specify the height and width of the
window, it will open the URL in a new separated window instead of a new tab:
To load another URL on an existing window, you pass an existing window name to
the window.open() method. The following example loads the contact.html webpage to
the contact window:
window.open('http://localhost/js/contact.html','about');
Code language: JavaScript (javascript)
Put it all together. The following code opens a new window that loads the
webpage about.html and then after 3 seconds, it loads the webpage contact.html in the same
window:
setTimeout(() => {
window.open('http://localhost/js/contact.html', 'about')
}, 3000);
Code language: JavaScript (javascript)
3) Resize a window
window.resizeTo(width,height);
Code language: JavaScript (javascript)
setTimeout(() => {
jsWindow.resizeTo(600, 300);
}, 3000);
Code language: JavaScript (javascript)
window.resizeBy(deltaX,deltaY);
Code language: JavaScript (javascript)
For example:
4) Move a window
window.moveTo(x, y);
Code language: JavaScript (javascript)
setTimeout(() => {
jsWindow.moveTo(500, 500);
}, 3000);
Code language: JavaScript (javascript)
setTimeout(() => {
jsWindow.moveBy(100, -100);
}, 3000);
Code language: JavaScript (javascript)
5) Close a window
window.open()
Code language: JavaScript (javascript)
The following example opens a new window and closes it after 3 seconds:
setTimeout(() => {
jsWindow.close();
}, 3000);
Code language: JavaScript (javascript)
6) The window.opener property
A newly created window can reference back to the window that opened it via
the window.opener property. This allows you to exchange data between the two windows.
Summary
Introduction to JavaScript alert() method
The browser can invoke a system dialog to display information to the user.
The system dialog is not related to the webpage being shown in the browser. It also
does not contain any HTML. Its appearance depends solely on the current operating
system and browser, rather than CSS.
window.alert(message);
Code language: JavaScript (javascript)
Or
alert(message);
The message is a string that contains information that you want to show to users.
For example:
alert('Welcome to JavaScriptTutorial.net!');
Code language: JavaScript (javascript)
When the alert() method is invoked, a system dialog shows the specified message to the
user followed by a single OK button.
You use the alert dialog to inform users something that they have no control over e.g.,
an error. The only choice that users can make is to dismiss the dialog after reading the
message.
Note that the alert dialog is synchronous and modal. It means that the code execution
stops when a dialog is displayed and resumes after it has been dismissed. For example,
the following code display an alert dialog after three seconds:
setTimeout(() => {
alert('3 seconds has been passed!')
}, 3000);
Code language: JavaScript (javascript)
Summary
JavaScript alert
Summary: in this tutorial, you will learn how to display an alert dialog by using the
JavaScript alert() method.
Introduction to JavaScript alert() method
The browser can invoke a system dialog to display information to the user.
The system dialog is not related to the webpage being shown in the browser. It also
does not contain any HTML. Its appearance depends solely on the current operating
system and browser, rather than CSS.
To invoke an alert system dialog, you invoke the alert() method of the window object.
window.alert(message);
Code language: JavaScript (javascript)
Or
alert(message);
The message is a string that contains information that you want to show to users.
For example:
alert('Welcome to JavaScriptTutorial.net!');
Code language: JavaScript (javascript)
When the alert() method is invoked, a system dialog shows the specified message to the
user followed by a single OK button.
You use the alert dialog to inform users something that they have no control over e.g.,
an error. The only choice that users can make is to dismiss the dialog after reading the
message.
Note that the alert dialog is synchronous and modal. It means that the code execution
stops when a dialog is displayed and resumes after it has been dismissed. For example,
the following code display an alert dialog after three seconds:
setTimeout(() => {
alert('3 seconds has been passed!')
}, 3000);
Code language: JavaScript (javascript)
Summary
JavaScript prompt
Summary: in this tutorial, you will learn how to use the JavaScript prompt() method to
display a dialog with a message prompting for user input.
Introduction to JavaScript prompt() method
The prompt() is a method of the window object. It invokes a dialog that has a text input field
and two buttons: OK and Cancel.
In this syntax:
The message is a string to display. If you omit it, nothing will display on the dialog.
The default is a string containing the default value of the text input field.
The result is a string that contains the text entered by the user or null.
JavaScript prompt() examples
The following example uses the prompt() to display a dialog that asks users for their
favorite programming languages:
alert(feedback);
Code language: JavaScript (javascript)
The result of the prompt() is a string. If you want to get the answer as a number, you
should always cast it.
The following example uses prompt() to display a dialog that asks users for their ages. If
users are 16 years old or above, they are eligible to join. Otherwise, they will not be.
alert(feedback);
Code language: JavaScript (javascript)
Summary
JavaScript setTimeout
Summary: in this tutorial, you will learn how to use the JavaScript setTimeout() that sets a
timer and executes a callback function after the timer expires.
Introduction to JavaScript setTimeout()
In this syntax:
JavaScript setTimeout() example
When you click the Show button, the showAlert() is invoked and shows an alert dialog after
3 seconds. To cancel the timeout, you click the Cancel button.
HTML
<p>JavaScript setTimeout Demo</p>
<button onclick="showAlert();">Show</button>
<button onclick="cancelAlert();">Cancel</button>
Code language: HTML, XML (xml)
JavaScript
var timeoutID;
function showAlert() {
timeoutID = setTimeout(alert, 3000, 'setTimeout Demo!');
}
function clearAlert() {
clearTimeout(timeoutID);
}
Code language: JavaScript (javascript)
Output
Show Cancel
How JavaScript setTimeout() works
JavaScript is single-threaded therefore it can only do one task at a time. It means that it
can only carry a single task a given time. Besides the JavaScript engine, the web browser
has other components such as Event Loop, Call Stack, and Web API.
When you call the setTimeout(), the JavaScript engine creates a new function execution
context and places it on the call stack.
The setTimeout() executes and creates a timer in the Web APIs component of the web
browser. When the timer expires, the callback function that was passed in
the setTimeout() is placed to the callback queue.
The event loop monitors both the call stack and the callback queue. It removes the
callback function from the callback queue and places it to call stack when the call stack
is empty.
function task() {
console.log('setTimeout Demo!')
}
setTimeout(task, 3000);
Code language: JavaScript (javascript)
In this example:
First, the setTimeout() is placed on the call stack. It creates a timer on Web API.
Second, after roughly 3 seconds, the timer expires, the task is pushed to the callback
queue and waited for the next opportunity to execute.
Third, because the call stack is empty, the event loop removes the task() from the callback
queue, places it on the call stack, and executes it:
Fourth, the console.log() in the setTimeout() executes that creates a new function execution
context.
Finally, the console.log() and task() are popped out of the call stack once they are
completed.
Summary
JavaScript setInterval
Summary: in this tutorial, you will learn how to use the JavaScript setInterval() to
repeatedly call a function with a fixed delay between each call.
Introduction to JavaScript setInterval()
In this syntax:
The setInterval() returns a numeric, non-zero number that identifies the created timer. You
can pass the intervalID to the clearInterval() to cancel the timeout.
JavaScript setInterval() example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>JavaScript setInterval Demo</title>
<script>
let intervalID;
function toggleColor() {
let e = document.getElementById('flashtext');
e.style.color = e.style.color == 'red' ? 'blue' : 'red';
}
function stop() {
clearInterval(intervalID);
}
function start() {
intervalID = setInterval(toggleColor, 1000);
}
</script>
</head>
<body>
<p id="flashtext">JavScript setInterval Demo</p>
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
</body>
</html>
Code language: HTML, XML (xml)
Output:
Start Stop
Summary
Section 2. Location
JavaScript Location
Summary: in this tutorial, you will learn about the JavaScript Location object and how to
manipulate the location effectively.
The Location object represents the current location (URL) of a document. You can access
the Location object by referencing the location property of the window or document object.
Both window.location and document.location link to the same Location object.
Location.href
"http://localhost:8080/js/index.html?type=listing&page=2#title"
Code language: JSON / JSON with Comments (json)
Location.protocol
The location.protocol represents the protocol scheme of the URL including the final colon ( :).
'http:'
Code language: JavaScript (javascript)
Location.host
"localhost:8080"
Code language: JSON / JSON with Comments (json)
Location.port
"8080"
Code language: JSON / JSON with Comments (json)
Location.pathname
"/js/index.html"
Code language: JSON / JSON with Comments (json)
Location.search
"?type=listing&page=2"
Code language: JSON / JSON with Comments (json)
Location.hash
"#title"
Code language: JSON / JSON with Comments (json)
Location.origin
The location.origin is a string that contains the canonical form of the origin of the specific
location.
"http://localhost:8080"
Code language: JSON / JSON with Comments (json)
Location.username
The location.username is a string that contains the username before the domain name.
Location.password
THe location.password is a string that represents the password specified before the domain
name.
Manipulating the location
assign()
The assign() method accepts an URL, navigate to the URL immediately, and make an entry
in the browser’s history stack.
location.assign('https://www.javascripttutorial.net');
Code language: JavaScript (javascript)
window.location = 'https://www.javascripttutorial.net';
location.href = 'https://www.javascripttutorial.net';
Code language: JavaScript (javascript)
If you change hostname, pathname, or port property, the page reloads with the new value.
Note that changing hash property doesn’t reload the page but does record a new entry
in the browser’s history stack.
When a new entry is created in the browser’s history stack, you can click the back button
of the browser to navigate to the previous page.
replace()
setTimeout(() => {
location.replace('https://www.javascripttutorial.net');
}, 3000);
Code language: JavaScript (javascript)
reload()
reload();
reload(true);
Code language: JavaScript (javascript)
Note that the code after the reload() may or may not execute, depending on many factors
like network latency and system resources. Therefore, it is a good practice to place
the reload() as the last line in the code.
Summary
location.search
Code language: CSS (css)
'?type=list&page=20'
Code language: JavaScript (javascript)
Output:
type:list
page:20
Code language: CSS (css)
Useful URLSearchParams methods
keys() example
The following example uses the keys() method to list all parameter names of a query
string:
Output:
type
page
values() example
The following example uses the keys() method to list all parameter values of a query
string:
Output:
list
20
Code language: PHP (php)
entries() example
The following example uses the entries() method to list all pairs of parameter key/value of
a query string:
Output:
["type", "list"]
["page", "20"]
Code language: JSON / JSON with Comments (json)
console.log(urlParams.has('type')); // true
console.log(urlParams.has('foo')); // false
Code language: JavaScript (javascript)
Output
true
false
Code language: JavaScript (javascript)
Summary
JavaScript Redirect
Summary: in this tutorial, you will learn how to use JavaScript to redirect to a new URL
or page.
Sometimes, you want to redirect users to a new URL e.g., after users log in, you want to
redirect them the admin homepage.
JavaScript has the APIs that allow you to redirect to a new URL or page. However,
JavaScript redirection runs entirely on the client-side therefore it doesn’t return the
status code 301 (move permanently) like server redirection.
If you move the site to a separate domain or create a new URL for an old page, it’s
better to use the server redirection.
To redirect to a new URL from the current page, you use the location object:
location.href = 'new_url';
Code language: JavaScript (javascript)
For example:
location.href = 'https://www.javascripttutorial.net/';
Code language: JavaScript (javascript)
Either of this call will redirect to the new URL and create an entry in the history stack of
the browser. It means that you can go back to the previous page via the Back button of
the browser.
To redirect to a new URL without creating a new entry in the history stack of the
browser, you use the replace() method of the location object:
location.replace('https://www.javascripttutorial.net/');
Code language: JavaScript (javascript)
The following script redirects to the about.html that is on the same level as the current
page.
location.href = 'about.html';
Code language: JavaScript (javascript)
location.href = '/contact.html';
Code language: JavaScript (javascript)
If you want to redirect to a new page upon loading, you use the following code:
window.onload = function() {
location.href = "https://www.javascripttutorial.net/";
}
Code language: JavaScript (javascript)
Summary
To redirect to a new URL or page, you assign the new URL to the location.href property or
use the location.assign() method.
The location.replace() method does redirect to a new URL but does not create an entry in
the history stack of the browser.
Sometimes, you want to redirect users to a new URL e.g., after users log in, you want to
redirect them the admin homepage.
JavaScript has the APIs that allow you to redirect to a new URL or page. However,
JavaScript redirection runs entirely on the client-side therefore it doesn’t return the
status code 301 (move permanently) like server redirection.
If you move the site to a separate domain or create a new URL for an old page, it’s
better to use the server redirection.
To redirect to a new URL from the current page, you use the location object:
location.href = 'new_url';
Code language: JavaScript (javascript)
For example:
location.href = 'https://www.javascripttutorial.net/';
Code language: JavaScript (javascript)
location.assign('https://www.javascripttutorial.net/');
Code language: JavaScript (javascript)
Either of this call will redirect to the new URL and create an entry in the history stack of
the browser. It means that you can go back to the previous page via the Back button of
the browser.
To redirect to a new URL without creating a new entry in the history stack of the
browser, you use the replace() method of the location object:
location.replace('https://www.javascripttutorial.net/');
Code language: JavaScript (javascript)
Redirect to a relative URL
The following script redirects to the about.html that is on the same level as the current
page.
location.href = 'about.html';
Code language: JavaScript (javascript)
location.href = '/contact.html';
Code language: JavaScript (javascript)
If you want to redirect to a new page upon loading, you use the following code:
window.onload = function() {
location.href = "https://www.javascripttutorial.net/";
}
Code language: JavaScript (javascript)
Summary
To redirect to a new URL or page, you assign the new URL to the location.href property or
use the location.assign() method.
The location.replace() method does redirect to a new URL but does not create an entry in
the history stack of the browser.
Section 3. Navigator
JavaScript Navigator
Summary: in this tutorial, you will learn about the JavaScript Navigator object and its
properties.
Introduction to the JavaScript Navigator object
The JavaScript Navigator provides information about the web browser and its
capabilities. You can reference the Navigator object via the read-
only window.navigator property.
The Navigator object has properties that convey the browser’s information. For example,
the userAgent is a property of the window.navigator object. It is a long string that identifies the
web browser.
window.navigator.userAgent
Code language: CSS (css)
Note that the userAgent may be a little bit different, depending on the Google Chrome
version.
The different web browser provides specific capabilities which are not standardized. It’s
better not to use the userAgent to identify the web browser because some web browsers
allow users to modify the userAgent to pretend they are using a different browser.
For example, you may use the following code to detect if the current web browser is
Internet Explorer:
if(navigator.userAgent.includes('MSIE')) {
// IE, use specific features of IE
} else {
// not IE
}
Code language: JavaScript (javascript)
To use a specific feature of a web browser, you can use the capability detection. For
example:
appVersion Returns the browser version. However, it typically does not correspond to the actual
version of the browser.
getUserMedia() Returns the stream associated with the available media device hardware.
Property / Method Description
locks Returns a LockManager object to interact with the Web Locks API.
mediaCapabilities Returns a MediaCapabilities object to interact with the Media capabilities API
maxTouchPoints Returns the maximum number of supported touch points for the device’s
touchscreen
oscpu The operating system (OS) and/or CPU on which the browser is running.
permissions Returns the Permissions object to interact with the Permissions API.
storage Returns the StorageManager object to interact with the Storage API.
JavaScript Screen
Summary: in this tutorial, you will learn how to use the JavaScript Screen object to get
the screen’s information of the current.
The Screen object provides the attributes of the screen on which the current window is
being rendered.
window.screen
Code language: JavaScript (javascript)
The Screen object is typically used by the web analytic software like Google Analytics to
collect information of the client device on which the web browsers are running.
JavaScript Screen properties
Property Description
availTop A read-only property that returns the first pixel from the top that is not taken up by system
elements.
availWidth A read-only property that returns the pixel width of the screen minus system elements.
colorDept A read-only property that returns the number of bits used to represent colors.
h
left Represents the pixel distance of the current screen’s left side.
pixelDepth A read-only property that returns the bit depth of the screen.
orientation Returns the screen orientation as specified in the Screen Orientation API
availTop A read-only property that returns the first pixel from the top that is not taken up by system
elements.
availWidth A read-only property that returns the pixel width of the screen minus system elements.
Property Description
colorDept A read-only property that returns the number of bits used to represent colors.
h
left Represents the pixel distance of the current screen’s left side.
orientation Returns the screen orientation as specified in the Screen Orientation API
JavaScript Screen
Summary: in this tutorial, you will learn how to use the JavaScript Screen object to get
the screen’s information of the current.
The Screen object provides the attributes of the screen on which the current window is
being rendered.
window.screen
Code language: JavaScript (javascript)
The Screen object is typically used by the web analytic software like Google Analytics to
collect information of the client device on which the web browsers are running.
JavaScript Screen properties
Property Description
availTop A read-only property that returns the first pixel from the top that is not taken up by system elements.
availWidth A read-only property that returns the pixel width of the screen minus system elements.
colorDepth A read-only property that returns the number of bits used to represent colors.
left Represents the pixel distance of the current screen’s left side.
pixelDepth A read-only property that returns the bit depth of the screen.
orientation Returns the screen orientation as specified in the Screen Orientation API
availTop A read-only property that returns the first pixel from the top that is not taken up by system elements.
availWidth A read-only property that returns the pixel width of the screen minus system elements.
colorDepth A read-only property that returns the number of bits used to represent colors.
left Represents the pixel distance of the current screen’s left side.
orientation Returns the screen orientation as specified in the Screen Orientation API
Section 5. History
JavaScript History
Summary: in this tutorial, you will learn how to access the browser’s session history by
using the JavaScript history object.
When you launch the web browser and open a new webpage, the web browser creates a
new entry in its history stack.
If you navigate to another webpage, the web browser also creates a new entry in the
history stack.
The history stack stores the current page and previous pages that you visited.
window.history
Code language: JavaScript (javascript)
For the security reason, it’s not possible to query the pages that a user have visited.
However, you can use the history object to navigate back and forth without knowing the
exact URL.
Using JavaScript history for navigation
The history object provides three methods for navigating between pages in the history
stack:
back()
forward()
go()
Move backward
window.history.back();
Code language: CSS (css)
Or
history.back();
Code language: CSS (css)
This behaves like you click the Back button in the toolbar of the web browser.
Move forward
history.forward();
Code language: CSS (css)
To move to a specific URL in the history stack, you use the go() method. The go() method
accepts an integer that is the relative position to the current page. The current page’s
position is 0.
history.go(-1);
Code language: CSS (css)
It is like the back() method.
To move forward a page, you just call:
history.go(1)
Code language: CSS (css)
history.go(0);
history.go();
Code language: CSS (css)
To determine the number of URLs in the history stack, you use the length property:
history.length
Code language: CSS (css)
Summary
JavaScript DOM
Section 1. Getting started
The Document Object Model (DOM) is an application programming interface (API) for
manipulating HTML and XML documents.
The DOM represents a document as a tree of nodes. It provides API that allows you to
add, remove, and modify parts of the document effectively.
Note that the DOM is cross-platform and language-independent ways of manipulating
HTML and XML documents.
The DOM represents an HTML or XML document as a hierarchy of nodes. Consider the
following HTML document:
<html>
<head>
<title>JavaScript DOM</title>
</head>
<body>
<p>Hello DOM!</p>
</body>
</html>
Code language: HTML, XML (xml)
Each document can have only one document element. In an HTML document, the
document element is the <html> element. Each markup can be represented by a node in
the tree.
Node Types
Each node in the DOM tree is identified by a node type. JavaScript uses integer numbers
to determine the node types.
Node.DOCUMENT_NODE 9 A Document node.
Node.DOCUMENT_FRAGMENT_NODE 11 A DocumentFragment node.
node.nodeType
Code language: CSS (css)
You can compare the nodeType property with the above constants to determine the node
type. For example:
if (node.nodeType == Node.ELEMENT_NODE) {
// node is the element node
}
Code language: JavaScript (javascript)
The nodeName and nodeValue properties
The values of these properites depends on the node type. For example, if the node type
is the element node, the nodeName is always the same as element’s tag name
and nodeValue is always null.
For this reason, it’s better to test node type before using these properties:
if (node.nodeType == Node.ELEMENT_NODE) {
let name = node.nodeName; // tag name like <p>
}
Code language: JavaScript (javascript)
A node is a generic name of any object in the DOM tree. It can be any built-in DOM
element such as the document. Or it can be any HTML tag specified in the HTML
document like <div> or <p>.
In other words, the node is generic type of the element. The element is a specific type of
the node with the node type Node.ELEMENT_NODE.
Node Relationships
Any node has relationships to other nodes in the DOM tree. The relationships are the
same as the one described in a traditional family tree.
JavaScript getElementById
Summary: in this tutorial, you will learn how to use the JavaScript getElementById() to
select an element by a specified id.
The id is used to uniquely identify an HTML element within the document. By rules, the
id root is unique within the document; no other elements can have this root id.
In this syntax, the id represents the id of the element that you want to select.
<html>
<head>
<title>JavaScript getElementById() Method</title>
</head>
<body>
<p id="message">A paragraph</p>
</body>
</html>
Code language: HTML, XML (xml)
The document contains a <p> element that has the id attribute with the value message:
const p = document.getElementById('message');
console.log(p);
Code language: JavaScript (javascript)
Output:
<p id="message">A paragraph</p>
Code language: HTML, XML (xml)
Once you selected an element, you can add styles to the element, manipulate
its attributes, and traversing to parent and child elements.
Summary
JavaScript getElementsByName
Summary: in this tutorial, you will learn how to use the
JavaScript getElementsByName() method to get elements with a given name in a document.
The following example shows a list of radio buttons that have the same name ( rate).
When you click the Rate button, the page will show an alert dialog that displays the
rating of the service such as Very Poor, Poor, OK, Good, and Very Good:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript getElementsByName Demo</title>
</head>
<body>
<p>Please rate the service:</p>
<p>
<input type="radio" name="rate" value="Very poor"> Very
poor
<input type="radio" name="rate" value="Poor"> Poor
<input type="radio" name="rate" value="OK"> OK
<input type="radio" name="rate" value="Good"> Good
<input type="radio" name="rate" value="Very Good"> Very
Good
</p>
<p>
<button id="btnRate">Submit</button>
</p>
<script>
let btn = document.getElementById('btnRate');
btn.addEventListener('click', () => {
let rates = document.getElementsByName('rate');
rates.forEach((rate) => {
if (rate.checked) {
alert(`You rated: ${rate.value}`);
}
})
});
</script>
</body>
</html>
Code language: HTML, XML (xml)
How it works:
Notice that you will learn about events like click later. For now, you just need to focus on
the getElementsByName() method.
Summary
JavaScript CreateElement
Summary: in this tutorial, you will learn how to use the
JavaScript document.createElement() to create a new HTML element and attach it to the DOM
tree.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS CreateElement Demo</title>
</head>
<body>
</body>
</html>
Code language: HTML, XML (xml)
document.body.appendChild(div);
Code language: CSS (css)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS CreateElement Demo</title>
</head>
<body>
<script>
let div = document.createElement('div');
div.id = 'content';
div.innerHTML = '<p>CreateElement example</p>';
document.body.appendChild(div);
</script>
</body>
</html>
Code language: HTML, XML (xml)
If you want to add an id to a div, you set the id attribute of the element to a value, like
this:
document.body.appendChild(div);
Code language: JavaScript (javascript)
document.body.appendChild(div);
Code language: JavaScript (javascript)
To add a piece of text to a <div>, you can use the innerHTML property as the above
example, or create a new Text node and append it to the div:
<ul id="menu">
<li>Home</li>
</ul>
Code language: HTML, XML (xml)
let li = document.createElement('li');
li.textContent = 'Products';
menu.appendChild(li);
li = document.createElement('li');
li.textContent = 'About Us';
Output:
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>
Code language: HTML, XML (xml)
Sometimes, you may want to load a JavaScript file dynamically. To do this, you can use
the document.createElement() to create the script element and add it to the document.
You can first create a new helper function that loads a JavaScript file from an URL:
function loadJS(url) {
let script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
Code language: JavaScript (javascript)
loadJS('/lib.js');
Code language: JavaScript (javascript)
function loadJSAsync(url) {
let script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
}
Code language: JavaScript (javascript)
Summary
JavaScript appendChild
Summary: in this tutorial, you will learn how to use the JavaScript appendChild() method to
add a node to the end of the list of child nodes of a specified parent node.
parentNode.appendChild(childNode);
Code language: CSS (css)
In this method, the childNode is the node to append to the given parent node.
The appendChild() returns the appended child.
JavaScript appendChild() examples
1) Simple appendChild() example
<ul id="menu">
</ul>
Code language: HTML, XML (xml)
function createMenuItem(name) {
let li = document.createElement('li');
li.textContent = name;
return li;
}
// get the ul#menu
const menu = document.querySelector('#menu');
// add menu item
menu.appendChild(createMenuItem('Home'));
menu.appendChild(createMenuItem('Services'));
menu.appendChild(createMenuItem('About Us'));
Code language: JavaScript (javascript)
How it works:
First, the createMenuItem() function create a new list item element with a specified name by
using the createElement() method.
Second, select the <ul> element with id menu using the querySelector() method.
Third, call the createMenuItem() function to create a new menu item and use
the appendChild() method to append the menu item to the <ul> element
Output:
<ul id="menu">
<li>Home</li>
<li>Services</li>
<li>About Us</li>
</ul>
Code language: HTML, XML (xml)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript appendChild() Demo</title>
</head>
<body>
<ul id="menu">
</ul>
<script>
function createMenuItem(name) {
let li = document.createElement('li');
li.textContent = name;
return li;
}
// get the ul#menu
const menu = document.querySelector('#menu');
// add menu item
menu.appendChild(createMenuItem('Home'));
menu.appendChild(createMenuItem('Services'));
menu.appendChild(createMenuItem('About Us'));
</script>
</body>
</html>
Code language: HTML, XML (xml)
<ul id="first-list">
<li>Everest</li>
<li>Fuji</li>
<li>Kilimanjaro</li>
</ul>
<ul id="second-list">
<li>Karakoram Range</li>
<li>Denali</li>
<li>Mont Blanc</li>
</ul>
Code language: HTML, XML (xml)
The following example uses the appendChild() to move the first child element from the first
list to the second list:
How it works:
Summary
Use appendChild() method to add a node to the end of the list of child nodes of a specified
parent node.
The appendChild() can be used to move an existing child node to the new position within
the document.
JavaScript textContent
Summary: in this tutorial, you will learn how to use the JavaScript textContent property to
get the text content of a node and its descendants.
Reading textContent from a node
To get the text content of a node and its descendants, you use the textContent property:
<div id="note">
JavaScript textContent Demo!
<span style="display:none">Hidden Text!</span>
<!-- my comment -->
</div>
Code language: HTML, XML (xml)
How it works.
Output:
As you can see clearly from the output, the textContent property returns the concatenation
of the textContent of every child node, excluding comments (and also processing
instructions).
textContent vs. innerText
On the other hand, the innerText takes the CSS style into account and returns only
human-readable text. For example:
Output:
As you can see, the hidden text and comments are not returned.
Since the innerText property uses the up-to-date CSS to compute the text, accessing it will
trigger a reflow, which is computationally expensive.
A reflow occurs when a web brower needs to process and draw parts or all of a
webpage again.
Setting textContent for a node
Besides reading textContent, you can also use the textContent property to set the text for a
node:
node.textContent = newText;
When you set textContent on a node, all the node’s children will be removed and replaced
by a single text node with the newText value. For example:
Summary
JavaScript innerHTML
Summary: in this tutorial, you will learn how to use the JavaScript innerHTML property of
an element to get or set an HTML markup contained in the element.
The innerHTML is a property of the Element that allows you to get or set the HTML markup
contained within the element.
To get the HTML markup contained within an element, you use the following syntax:
When you read the innerHTML of an element, the web browser has to serialize the HTML
fragment of the element’s descendants.
1) Simple innerHTML example
<ul id="menu">
<li>Home</li>
<li>Services</li>
</ul>
Code language: HTML, XML (xml)
The following example uses the innerHTML property to get the content of
the <ul> element:
How it works:
Output:
<li>Home</li>
<li>Services</li>
Code language: HTML, XML (xml)
The innerHTML property returns the current HTML source of the document, including all
changes have been made since the page was loaded.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript innerHTML</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>Services</li>
</ul>
<script>
let menu = document.getElementById('menu');
console.log(menu.innerHTML);
</script>
</body>
</html>
Code language: HTML, XML (xml)
Output:
<li>Home</li>
<li>Services</li>
<li>About Us</li>
Code language: HTML, XML (xml)
How it works.
element.innerHTML = newHTML;
The setting will replace the existing content of an element with the new content.
For example, you can remove the entire contents of the document by clearing contents
of the document.body element:
document.body.innerHTML = '';
Code language: JavaScript (javascript)
⚠️Security Risk
HTML5 specifies that a <script> tag inserted with innerHTML should not execute. See
the following example:
index.html document:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript innerHTML</title>
</head>
<body>
<div id="main"></div>
<script src="app.js"></script>
</body>
</html>
Code language: HTML, XML (xml)
app.js
Therefore, you should not set the innerHTML to the content that you have no control over
or you will face a potential security risk.
Because of this, if you want to insert plain text into the document, you use
the textContent property instead of the innerHTML. The textContent will not be parsed as the
HTML, but as the raw text.
Summary
<div class="container"></div>
Code language: HTML, XML (xml)
You can new elements to the div element by creating an element and appending it:
let p = document.createElement('p');
p.textContent = 'JS DOM';
div.appendChild(p);
Code language: JavaScript (javascript)
Using innerHTML is cleaner and shorter when you want to add attributes to the element:
However, using the innerHTML causes the web browsers to reparse and recreate all DOM
nodes inside the div element. Therefore, it is less efficient than creating a new element
and appending to the div. In other words, creating a new element and appending it to
the DOM tree provides better performance than the innerHTML.
As mentioned in the innerHTML tutorial, you should use it only when the data comes
from a trusted source like a database.
If you set the contents that you have no control over to the innerHTML, the malicious
code may be injected and executed.
Assuming that you have a list of elements and you need in each iteration:
This code results in recalculation of styles, painting, and layout every iteration. This is
not very efficient.
To overcome this, you typically use a DocumentFragment to compose DOM nodes and
append it to the DOM tree:
A document fragment does not link to the active DOM tree, therefore, it doesn’t incur
any performance.
JavaScript DocumentFragment
Summary: in this tutorial, you’ll learn about the JavaScript DocumentFragment interface to
compose DOM nodes and update them to the active DOM tree.
If you make changes to the document fragment, it doesn’t affect the document or incurs
any performance.
Typically, you use the DocumentFragment to compose DOM nodes and append or insert it to
the active DOM tree using appendChild() or insertBefore() method.
<ul id="language"></ul>
Code language: HTML, XML (xml)
The following code creates a list of <li> elements (<li>) and append each to
the <ul> element using the DocumentFragment:
langEl.appendChild(fragment);
Code language: JavaScript (javascript)
How it works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>DocumentFragment Demo</title>
</head>
<body>
<ul id="language"></ul>
<script>
let languages = ['JS', 'TypeScript', 'Elm', 'Dart',
'Scala'];
languages.forEach((language) => {
let li = document.createElement('li');
li.innerHTML = language;
fragment.appendChild(li);
})
langEl.appendChild(fragment);
</script>
</body>
</html>
Code language: HTML, XML (xml)
Summary
Use the DocumentFragment to compose DOM nodes before updating them to the active
DOM tree to get better performance.
JavaScript insertBefore
Summary: in this tutorial, you will learn how to use the JavaScript insertBefore() to insert a
node before another node as a child node of a specified parent node.
Introduction to JavaScript insertBefore() method
To insert a node before another node as a child node of a parent node, you use
the parentNode.insertBefore() method:
parentNode.insertBefore(newNode, existingNode);
Code language: CSS (css)
In this method:
JavaScript insertBefore() helper function
<ul id="menu">
<li>Services</li>
<li>About</li>
<li>Contact</li>
</ul>
Code language: HTML, XML (xml)
The following example uses the insertBefore() method to insert a new node as the first list
item:
How it works.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript insertBefore()</title>
</head>
<body>
<ul id="menu">
<li>Services</li>
<li>About</li>
<li>Contact</li>
</ul>
<script>
let menu = document.getElementById('menu');
// create a new li node
let li = document.createElement('li');
li.textContent = 'Home';
</html>
Code language: HTML, XML (xml)
Summary
JavaScript insertAfter
Summary: in this tutorial, you will learn how to insert a new node after an existing node
as a child node of a parent node.
JavaScript DOM provides the insertBefore() method that allows you to insert a new after
an existing node as a child node. However, it hasn’t supported the insertAfter() method
yet.
To insert a new node after an existing node as a child node, you can use the following
approach:
The following snippet inserts a new node after the first list item:
How it works:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript insertAfter() Demo</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
<script>
let menu = document.getElementById('menu');
// create a new li node
let li = document.createElement('li');
li.textContent = 'Services';
// insert a new node after the first list item
menu.insertBefore(li,
menu.firstElementChild.nextSibling);
</script>
</body>
</html>
Code language: HTML, XML (xml)
Summary
JavaScript append
Summary: in this tutorial, you’ll learn how to use the JavaScript append() method to insert
a set of Node objects or DOMString objects after the last child of a parent node.
parentNode.append(...nodes);
parentNode.append(...DOMStrings);
Code language: JavaScript (javascript)
<ul id="app">
<li>JavaScript</li>
</ul>
Code language: HTML, XML (xml)
The following example shows how to create a list of li elements and append them to
the ul element:
app.append(...nodes);
Code language: JavaScript (javascript)
Output HTML:
<ul id="app">
<li>JavaScript</li>
<li>TypeScript</li>
<li>HTML</li>
<li>CSS</li>
</ul>
Code language: HTML, XML (xml)
How it works:
console.log(app.textContent);
Code language: JavaScript (javascript)
Output HTML:
Summary
JavaScript append
Summary: in this tutorial, you’ll learn how to use the JavaScript append() method to insert
a set of Node objects or DOMString objects after the last child of a parent node.
Introduction to JavaScript append() method
parentNode.append(...nodes);
parentNode.append(...DOMStrings);
Code language: JavaScript (javascript)
<ul id="app">
<li>JavaScript</li>
</ul>
Code language: HTML, XML (xml)
The following example shows how to create a list of li elements and append them to
the ul element:
app.append(...nodes);
Code language: JavaScript (javascript)
Output HTML:
<ul id="app">
<li>JavaScript</li>
<li>TypeScript</li>
<li>HTML</li>
<li>CSS</li>
</ul>
Code language: HTML, XML (xml)
How it works:
<div id="app"></div>
Code language: HTML, XML (xml)
console.log(app.textContent);
Code language: JavaScript (javascript)
Output HTML:
Summary
JavaScript prepend
Summary: in this tutorial, you’ll learn about the JavaScript prepend() method that
inserts Node objects or DOMString objects before the first child of a parent node.
parentNode.prepend(...nodes);
parentNode.prepend(...DOMStrings);
Code language: JavaScript (javascript)
The prepend() method returns undefined.
<ul id="app">
<li>HTML</li>
</ul>
Code language: HTML, XML (xml)
This example shows how to create a list of li elements and prepend them to
the ul element:
app.prepend(...nodes);
Code language: JavaScript (javascript)
Output HTML:
<ul id="app">
<li>CSS</li>
<li>JavaScript</li>
<li>TypeScript</li>
<li>HTML</li>
</ul>
Code language: HTML, XML (xml)
How it works:
<div id="app"></div>
Code language: HTML, XML (xml)
The following shows how to use the prepend() method to prepend a text to the
above div element:
console.log(app.textContent);
Code language: JavaScript (javascript)
Output HTML:
Summary
JavaScript insertAdjacentHTML
Summary: in this tutorial, you’ll learn how to use the insertAdjacentHTML() method to insert
HTML into the document.
element.insertAdjacentHTML(positionName, text);
Code language: JavaScript (javascript)
1) position
Note that the 'beforebegin' and 'afterend' are only relevant if the element is in the DOM tree
and has a parent element.
2) text
Security consideration
Like the innerHTML, if you use the user input to pass into the insertAdjacentHTML() method,
you should always escape it to avoid security risk.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>insertAdjacentHTML() Demo</title>
</head>
<body>
<ul id="list">
<li>CSS</li>
</ul>
<script>
let list = document.querySelector('#list');
list.insertAdjacentHTML('beforebegin', '<h2>Web
Technology</h2>');
list.insertAdjacentHTML('afterbegin', '<li>HTML</li>');
list.insertAdjacentHTML('beforeend',
'<li>JavaScript</li>');
list.insertAdjacentHTML('afterend', '<p>For frontend
developers</p>');
</script>
</body>
</html>
How it works:
Summary
JavaScript replaceChild
Summary: in this tutorial, you will learn how to use the
JavaScript Node.replaceChild() method to replace an HTML element by a new one.
parentNode.replaceChild(newChild, oldChild);
Code language: CSS (css)
In this method, the newChild is the new node to replace the oldChild node which is the old
child node to be replaced.
<ul id="menu">
<li>Homepage</li>
<li>Services</li>
<li>About</li>
<li>Contact</li>
</ul>
Code language: HTML, XML (xml)
The following example creates a new list item element and replaces the first list item
element in the menu by the new one:
menu.replaceChild(li, menu.firstElementChild);
Code language: JavaScript (javascript)
Put it all together.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript DOM: Replace Elements</title>
</head>
<body>
<ul id="menu">
<li>Homepage</li>
<li>Services</li>
<li>About</li>
<li>Contact</li>
</ul>
<script>
let menu = document.getElementById('menu');
// create a new node
let li = document.createElement('li');
li.textContent = 'Home';
// replace the first list item
menu.replaceChild(li, menu.firstElementChild);
</script>
</body>
</html>
Code language: HTML, XML (xml)
Summary
JavaScript cloneNode
Summary: in this tutorial, you will learn how to use the JavaScript cloneNode() method to
clone an element.
deep
If the deep is true, then the original node and all of its descendants are cloned.
If the deep is false, only the original node will be cloned. All the node’s descendants
will not be cloned.
originalNode
Return value
Usage notes
Besides the DOM structure, the cloneNode() copies all attributes and inline listeners of the
original node. However, it doesn’t copy the event listeners added via addEventListener() or
assignment to element’s properties such as originalNode.onclick = eventHandler().
If you clone a node with an id attribute and place the cloned node in the same
document, the id will be duplicate. In this case, you need to change the id before adding
it to the DOM tree.
JavaScript cloneNode() example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript cloneNode() Demo</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>Services</li>
<li>About</li>
<li>Contact</li>
</ul>
<script>
let menu = document.querySelector('#menu');
let clonedMenu = menu.cloneNode(true);
clonedMenu.id = 'menu-mobile';
document.body.appendChild(clonedMenu);
</script>
</body>
</html>
Code language: HTML, XML (xml)
How it works.
JavaScript removeChild
Summary: in this tutorial, you will learn how to use the JavaScript removeChild() method to
remove a child node from a parent node.
Introduction to JavaScript removeChild() method
If you don’t want to keep the removed child node in the memory, you use the following
syntax:
parentNode.removeChild(childNode);
Code language: CSS (css)
The child node will be in the memory until it is destroyed by the JavaScript garbage
collector.
JavaScript removeChild() example
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>
Code language: HTML, XML (xml)
The following example uses the removeChild() to remove the last list item:
How it works:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript removeChild()</title>
</head>
<body>
<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>
<script>
let menu = document.getElementById('menu');
menu.removeChild(menu.lastElementChild);
</script>
</body>
</html>
Code language: HTML, XML (xml)
To remove all child nodes of an element, you use the following steps:
The following code shows how to remove all list items of the menu element:
You can remove all child nodes of an element by setting the innerHTML property of the
parent node to blank:
Summary
JavaScript Events
Summary: in this tutorial, you will learn about the JavaScript events, event models, and
how to handle events.
Introduction to JavaScript events
An event is an action that occurs in the web browser, which the web browser feedbacks
to you so that you can respond to it.
For example, when users click a button on a webpage, you may want to respond to
this click event by displaying a dialog box.
Each event may have an event handler which is a block of code that will execute when
the event occurs.
An event handler is also known as an event listener. It listens to the event and executes
when the event occurs.
To define the code that will be executed when the button is clicked, you need to register
an event handler using the addEventListener() method:
function display() {
alert('It was clicked!');
}
btn.addEventListener('click',display);
Code language: JavaScript (javascript)
How it works.
A shorter way to register an event handler is to place all code in an anonymous function,
like this:
btn.addEventListener('click',function() {
alert('It was clicked!');
});
Code language: JavaScript (javascript)
Event flow
<!DOCTYPE html>
<html>
<head>
<title>JS Event Demo</title>
</head>
<body>
<div id="container">
<button id='btn'>Click Me!</button>
</div>
</body>
Code language: HTML, XML (xml)
When you click the button, you’re clicking not only the button but also the button’s
container, the div, and the whole webpage.
Event flow explains the order in which events are received on the page from the element
where the event occurs and propagated through the DOM tree.
There are two main event models: event bubbling and event capturing.
Event bubbling
In the event bubbling model, an event starts at the most specific element and then flows
upward toward the least specific element (the document or even window).
When you click the button, the click event occurs in the following order:
1. button
2. div with the id container
3. body
4. html
5. document
The click event first occurs on the button which is the element that was clicked. Then
the click event goes up the DOM tree, firing on each node along its way until it reaches
the document object.
The following picture illustrates the event bubbling effect when users click the button:
Event capturing
In the event capturing model, an event starts at the least specific element and flows
downward toward the most specific element.
When you click the button, the click event occurs in the following order:
1. document
2. html
3. body
4. div with the id container
5. button
DOM level 2 events specify that event flow has three phases:
First, event capturing occurs, which provides the opportunity to intercept the event.
Then, the actual target receives the event.
Finally, event bubbling occurs, which allows a final response to the event.
The following picture illustrates the DOM Level 2 event model when users click the
button:
Event object
When the event occurs, the web browser passed an Event object to the event handler:
btn.addEventListener('click', function(event) {
console.log(event.type);
});
Code language: JavaScript (javascript)
Output:
'click'
Code language: JavaScript (javascript)
The following table shows the most commonly-used properties and methods of
the event object:
Property / Description
Method
preventDefault() cancel the default behavior for the event. This method is only effective if
the cancelable property is true
stopPropagation() cancel any further event capturing or bubbling. This method only can be used if
the bubbles property is true.
Note that the event object is only accessible inside the event handler. Once all the event
handlers have been executed, the event object is automatically destroyed.
preventDefault()
For example, when you click a link, the browser navigates you to the URL specified in
the href attribute:
<a href="https://www.javascripttutorial.net/">JS Tutorial</a>
Code language: HTML, XML (xml)
link.addEventListener('click',function(event) {
console.log('clicked');
event.preventDefault();
});
Code language: JavaScript (javascript)
Note that the preventDefault() method does not stop the event from bubbling up the DOM.
And an event can be canceled when its cancelable property is true.
stopPropagation()
btn.addEventListener('click', function(event) {
console.log('The button was clicked!');
event.stopPropagation();
});
document.body.addEventListener('click',function(event) {
console.log('The body was clicked!');
});
Code language: JavaScript (javascript)
Summary
An event is an action that occurs in the web browser e.g., a mouse click.
Event flow has two main models: event bubbling and event capturing.
DOM Level 2 Event specifies that the event flow has three phases: event bubbling, the
event occurs at the exact element, and event capturing.
Use addEventListener() to register an event that connects an event to an event listener
The event object is accessible only within the event listener.
Use preventDefault() method to prevent the default behavior of an event, but does not
stop the event flow.
Use stopPropagation() method to stop the flow of an event through the DOM tree, but does
not cancel the browser default behavior.