Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
258 views

JavaScript DOM

This document covers the JavaScript Document Object Model (DOM) and how to manipulate DOM elements. It includes sections on selecting elements by ID, name, tag, or CSS; traversing to get parent, child and sibling elements; manipulating elements by creating, inserting, removing and cloning nodes; working with attributes, styles and events; and scripting forms. Code snippets are provided for common DOM tasks like selection, traversal, manipulation, and event handling.

Uploaded by

Elias Libay
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
258 views

JavaScript DOM

This document covers the JavaScript Document Object Model (DOM) and how to manipulate DOM elements. It includes sections on selecting elements by ID, name, tag, or CSS; traversing to get parent, child and sibling elements; manipulating elements by creating, inserting, removing and cloning nodes; working with attributes, styles and events; and scripting forms. Code snippets are provided for common DOM tasks like selection, traversal, manipulation, and event handling.

Uploaded by

Elias Libay
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 108

JavaScript DOM

GETTING STARTED

 Introduction to Document Object Model

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

 Get the Parent Element


 Get Siblings of an Element
 Get Children of an Element

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

 HTML Attributes & DOM Properties


 Set Value of an Attribute
 Get Value of an Attribute
 Remove an Attribute from Elements
 Check if an Element has an Attribute
STYLING

 Get or Set Inline Style


 Get the Computed Style
 Get CSS Classes
 Manipulate CSS Classes
 Get Element’s Width and Height

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

 Form: submit & reset


 Checkbox
 Radio Button
 Select Box
 Add & Remove Options

MINI PROJECTS

 Toggle Password Visibility


 Wikipedia Search App
 Word Counter App
 Javascript Form Validation
 Countdown Timer
 Infinite Scroll
This section covers the JavaScript Document Object Model (DOM) and shows you how
to manipulate DOM elements effectively.

Section 1. Getting started

 Understanding the Document Object Model in JavaScript

Section 2. Selecting elements

 getElementById() – select an element by id.


 getElementsByName() – select elements by name.
 getElementsByTagName()  – select elements by a tag name.
 getElementsByClassName() – select elements by one or more class names.
 querySelector()  – select elements by CSS selectors.

Section 3. Traversing elements

 Get the parent element – get the parent node of an element.


 Get child elements – get children of an element.
 Get siblings of an element – get siblings of an element.

Section 4. Manipulating elements

 createElement() – create a new element.


 appendChild()  – append a node to a list of child nodes of a specified parent node.
 textContent – get and set the text content of a node.
 innerHTML – get and set the HTML content of an element.
 innerHTML vs. createElement – explain the differences beetween innerHTML and
createElement when it comes to creating new elements.
 DocumentFragment – learn how to compose DOM nodes and insert them into the active
DOM tree.
 insertBefore() – insert a new node before an existing node as a child node of a specified
parent node.
 insertAfter() helper function – insert a new node after an existing node as a child node of
a specified parent node.
 append() – insert a node after the last child node of a parent node.
 prepend() – insert a node before the first child node of a parent node.
 insertAdjacentHTML() – parse a text as HTML and insert the resulting nodes into the
document at a specified position.
 replaceChild() – replace a child element by a new element.
 cloneNode() – clone an element and all of its descendants.
 removeChild() – remove child elements of a node.
Section 5. Working with Attributes

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

Section 6. Manipulating Element’s Styles

 style property – get or set inline styles of an element.


 getComputedStyle() – return the computed style of an element.
 className property – return a list of space-separated CSS classes.
 classList property – manipulate CSS classes of an element.
 Element’s width & height – get the width and height of an element.

Section 7. Working with Events

 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

 An Essential Guide to JavaScript null


 How to Check if an Array Contains a Value in Javascript
 How to Check If a Variable is an Array in JavaScript
 How to Replace All Occurrences of a Substring in a String
 How to Check if Two Strings are Equal in JavaScript
 3 Ways to Check If a Property Exists in an Object
 Top 3 Practical Ways to Perform Javascript String Concatenation
 Detect Caps Lock Is On
 Get the Scrollbar Width of an Element
 Check If the Document is Ready

JavaScript Snippets
DOM

This section provides you with handy functions for selecting, traversing, and
manipulating DOM elements.

Selecting
Selecting an Element By Id

Select an element that matches the id using the getElementById() method.

Selecting Elements By Tag Name

Select elements that match a tag name using the getElementsByTagName() method.

Selecting Elements By Class Name

Select elements that match a class name using the getElementsByClassName method.

Selecting Elements By Name

This tutorial shows you how to select elements by name using the JavaScript
getElementsByName() method

Selecting Elements By CSS Selector

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.

Get the Closest Element by Selector

Get the closest element tht match a selector.

Get Siblings of an Element

Provide a helper function that returns all siblings of an element.

Get the Children of an Element

Get all the child elements of an element


Manipulating
This section shows you how to add, remove, copy DOM elements

Create a DOM Element

Create a new Element and add it to the DOM tree.

Clone an Element

Clone an element and all of its descendants.

Insert an Element After Another

Insert an element after another in the DOM tree.

Insert an Element Before Another

Insert a new element before another in the DOM tree.

Get and Set the Text Content of an Element

Get or set the text content of an Element using the textContent property.

Get and Set the HTML Content of an Element

Get and set the HTML of an element using the innerHTML property.

Replace a DOM Element

Replace an element by a new one.

Remove a DOM Element

Remove an element from the DOM tree using the removeChild() method.

Remove All Child Nodes

Provide a helper function that remove all child nodes of a node.


Iterate Over Selected Elements

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 Exists

Check if an attribute with a specified name exists using the hasAttribute() method.

Remove an Attribute from an Element

Remove an attribute from an element using the removeAttribute() method.

Set the Value of an Attribute

Set a value for an attribute of an element using the setAttribute() method.

Get the Value of an Attribute

Get the attribute value of an element using the getAttribute() method

CSS
This section shows you how to manipulate the element’s CSS using JavaScript DOM methods.

Get the Scrollbar Width of an Element

This tutorial shows you how to get the scrollbar width of an element in JavaScript.

Check If an Element is Visible in the Viewport

In this tutorial, you’ll learn how to check if an element is visible in the viewport using
JavaScript.

Replace a Class of an Element

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.

Toggle a Class of an Element

This tutorial shows you how toggle a class of an element using the JavaScript DOM API.

Remove a Class from an Element

This tutorial shows you how to remove one or more classes from an element using JavaScript
DOM API.

Add a Class to an Element

This tutorial shows you how to add one or more classes to an element in JavaScript

Get Width and Height of an Element

This tutorial shows you how to get the width and height of an element using JavaScript DOM
API.

Get the Offset Position of an element Relative to Its Parent

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:

Get the Width and Height of the Window

This tutorial shows you how to get the width and height of the window in JavaScript

Get and Set Scroll Position of the Document

This tutorial shows you how to get and set the scroll position of the document.

Get and Set Scroll Position of an Element

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

Get the computed styles of an element by using the getComputedStyle() method.

How to Add Styles to 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.

Detect Caps Lock Is On

This tutorial shows you how to detect if the caps lock is on using JavaScript DOM API.

Check If the Document is Ready

This tutoial shows you how to check if the document is ready using vanilla JavaScript.

Add an Event Handler

This tutorial shows you how to attach an event handler to an event of an element in JavaScript.

Remove an Event Handler

This tutorial shows you how to use the removeEventListener() method to remove an event
handler from an event of an element.

Create a One-Off Event Handler

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.

Detect If an Element has focus

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.

Stop Propagation of Events

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.

How to Check If a Variable is an Array 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

Remove Duplicates from an Array

In this tutorial, you will learn some techniques to to remove duplicates from an array in
JavaScript.

Sort an Array of Objects in JavaScript

In this tutorial, you will learn how to sort an array of objects by the values of the object’s
properties

4 Ways to Empty an Array in JavaScript

This tutorial shows you various ways to empty an array in JavaScript

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.

JavaScript Merge Objects

Merge objects into a single object using the spread operator (…) or Object.assign() method.

Iterate Object in JavaScript

Iterate object’s properties using the for…in loop

Convert an Object to an Array in JavaScript

Convert an object to an array using Object.keys(), Object.values(), and Object.entries() methods.

3 Ways to Copy Objects in JavaScript

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

The global object of JavaScript in the browser is the window object. It means that


all variables and functions declared globally with the var keyword become
the properties and methods of the window object. For example:

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.

The window object exposes the browser’s functionality

The window object exposes the functionality of the web browser to the webpage.

1) Window size

The window object has four properties related to the size of the window:

 The innerWidth and innerHeight properties return the size of the page viewport inside the


browser window (not including the borders and toolbars).
 The outerWidth and outerHeight properties return the size of the browser window itself.

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:

const width = window.innerWidth


|| document.documentElement.clientWidth
|| document.body.clientWidth;

const height = window.innerHeight


|| document.documentElement.clientHeight
|| document.body.clientHeight;
Code language: JavaScript (javascript)

2) Open a new window

To open a new window or tab, you use the window.open() method:

window.open(url, windowName, [windowFeatures]);


Code language: CSS (css)

The window.open() method accepts three arguments: the URL to load, the window target
and a string of window features.

The third argument is a command-delimited string of settings specifying displaying


information for the new window such as width, height, menubar, and resizable.

The window.open() method returns a WindowProxy object, which is a thin wrapper of


the window object. In case the new window cannot be opened, it returns null.
For example, to open a new window that loads the page about.html at localhost, you use
the following code:

let url = 'http://localhost/js/about.html';


let jsWindow = window.open(url,'about');
Code language: JavaScript (javascript)

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:

let features = 'height=600,width=800',


url = 'http://localhost/js/about.html';

let jsWindow = window.open(url, 'about', features);


Code language: JavaScript (javascript)

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:

let features = 'height=600,width=800',


url = 'http://localhost/js/about.html';

let jsWindow = window.open(url, 'about', features);

setTimeout(() => {
window.open('http://localhost/js/contact.html', 'about')
}, 3000);
Code language: JavaScript (javascript)

3) Resize a window

To resize a window you use the resizeTo() method of the window object:

window.resizeTo(width,height);
Code language: JavaScript (javascript)

The following example opens a new window that loads the http://localhost/js/about.html page


and the resize the window to (600,300) after 3 seconds:
let jsWindow = window.open(
'http://localhost/js/about.html',
'about',
'height=600,width=800');

setTimeout(() => {
jsWindow.resizeTo(600, 300);
}, 3000);
Code language: JavaScript (javascript)

The window.resizeBy() method allows you to resize the current window by a specified


amount:

window.resizeBy(deltaX,deltaY);
Code language: JavaScript (javascript)

For example:

let jsWindow = window.open(


'http://localhost/js/about.html',
'about',
'height=600,width=600');

// shrink the window, or resize the window


// to 500x500
setTimeout(() => {
jsWindow.resizeTo(-100, -100);
}, 3000);
Code language: JavaScript (javascript)

4) Move a window

To move a window to a specified coordinate, you use the moveTo() method:

window.moveTo(x, y);
Code language: JavaScript (javascript)

In this method, x and y are horizontal and vertical coordinates to be moved to. The


following example opens a new window and moves it to (0,0) coordinate after 3 seconds:

let jsWindow = window.open(


'http://localhost/js/about.html',
'about',
'height=600,width=600');

setTimeout(() => {
jsWindow.moveTo(500, 500);
}, 3000);
Code language: JavaScript (javascript)

Similarly, you can move the current window by a specified amount:

let jsWindow = window.open(


'http://localhost/js/about.html',
'about',
'height=600,width=600');

setTimeout(() => {
jsWindow.moveBy(100, -100);
}, 3000);
Code language: JavaScript (javascript)

5) Close a window

To close a window, you use the window.open() method:

window.open()
Code language: JavaScript (javascript)

The following example opens a new window and closes it after 3 seconds:

let jsWindow = window.open(


'http://localhost/js/about.html',
'about',
'height=600,width=600');

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

 The window is the global object in the web browser.


 The window object exposes the functionality of the web browser.
 The window object provides methods for manipulating a window such
as open(), resize(), resizeBy(), moveTo(), moveBy(), and close().
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.

Click here to show the alert system dialog.

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

 The alert() is a method of the window object.


 The alert() method is modal and synchronous.
 Use the alert() method to display information that you want users to acknowledge.

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.

Click here to show the alert system dialog.

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

 The alert() is a method of the window object.


 The alert() method is modal and synchronous.
 Use the alert() method to display information that you want users to acknowledge.

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.

The following illustrates the syntax of the prompt() method:

let result = window.prompt(message, default);


Code language: JavaScript (javascript)

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.

Like alert() and confirm(), the prompt() is modal and synchronous. In other words, the code


execution stops when the dialog is displayed and resumes after the dialog has been
dismissed.

JavaScript prompt() examples

Let’s take some examples to see how the prompt() works.

1) Display a prompt dialog

The following example uses the prompt() to display a dialog that asks users for their
favorite programming languages:

let lang = prompt('What is your favorite programming language?');


let feedback = lang.toLowerCase() === 'javascript' ? `It's great!
` :
`It's ${lang}`;

alert(feedback);
Code language: JavaScript (javascript)

Click here to see the code in action

2) Convert a user input to a number

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.

let ageStr = prompt('How old are you?');


let age = Number(ageStr);

let feedback = age >= 16 ?


`You're eligible to join.` :
`You must be at least 16 year old to join.`;

alert(feedback);
Code language: JavaScript (javascript)

Click here to see the code in action

Summary

 The prompt() is a method of the window object.


 The prompt() shows a dialog that has a text input field and two buttons: OK and Cancel.
 The prompt() returns a string containing a string entered by the user or null if the user did
not enter anything.

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

The setTimeout() is a method of the window object. The setTimeout()  sets a timer and executes


a callback function after the timer expires.

The following illustrates the syntax of setTimeout():

let timeoutID = setTimeout(cb [,delay], arg1, arg2,...);


Code language: JavaScript (javascript)

In this syntax:

  cb is a callback function to be executed after the timer expires.


 delay is the time in milliseconds that the timer should wait before executing the
callback function. If you omit it, the delay defaults to 0.
 arg1, arg2, … are arguments passed to the cb callback function.

The setTimeout() returns a timeoutID which is a positive integer identifying the timer created


as a result of calling the method.

The timeoutID can be used to cancel timeout by passing it to the clearTimeout() method.

JavaScript setTimeout() example

The following creates two simple buttons and hooks them to


the setTimeout() and clearTimeout().

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

JavaScript setTimeout Demo

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.

Once the callback function is on the call stack, it is executed.

See the following example:

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

 setTimeout() is a method of the window object.


 setTimeout() sets a timer and executes a callback function when the timer expires.

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

The setInterval() is a method of the window object. The setInterval() repeatedly calls a function


with a fixed delay between each call.

The following illustrates the syntax of the setInterval():

let intervalID = setInterval(callback, delay,[arg1, arg2, ...]);


Code language: JavaScript (javascript)

In this syntax:

 The callback is a callback function to be executed every delay milliseconds.


 The delay is the time (in milliseconds) that the timer should delay between executions of
the callback function.
 The arg1, … argN are the arguments that are passed to the callback function.

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.

Note that the setInterval() works like the setTimeout() but it repeatedly executes a callback


once every specified delay.

JavaScript setInterval() example

The following example uses the setInterval() and clearInterval() to change the color of a


heading once a second once you press the Start button. If you stop the button,
the clearInterval() will cancel the timeout.

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

JavaScript setInterval Demo

Start Stop

Summary

 The setInterval() repeatedly calls a function once a fixed delay between each call.


 The setInterval() returns a timeoutID that can be passed to the clearInterval() to cancel the
timeout.

Section 2. Location

 Location – manipulate the location of a document via the location object.


 Get query string parameters – learn how to retrieve query string parameters.
 Redirect to a new URL – show you how to redirect to a new URL using JavaScript.

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.

JavaScript Location properties

Suppose that the current URL is:

Location.href

The location.href is a string that contains the entire URL.

"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

The location.host represents the hostname:

"localhost:8080"
Code language: JSON / JSON with Comments (json)
Location.port

The location.port represents the port number of the URL.

"8080"
Code language: JSON / JSON with Comments (json)

Location.pathname

The location.pathname contains an initial '/' followed by the path of the URL.

"/js/index.html"
Code language: JSON / JSON with Comments (json)

Location.search

The location.search is a string that represents the query string of the URL:

"?type=listing&page=2"
Code language: JSON / JSON with Comments (json)

Location.hash

The location.hash returns a string that contains a ‘#’ followed by the fragment identifier of


the URL.

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

The Location object has a number of useful methods: assign(), reload(), and replace().

 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)

When the window.location or location.href is set to a URL, the assign() method is called


implicitly:

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

The replace() method is similar to the assign() method except it doesn’t create a new entry


in the browser’s history stack. Therefore, you cannot click the back button to go to the
previous page.

The following code uses the replace() method to navigate to the


URL https://www.javascripttutorial.net after 3 seconds:

setTimeout(() => {
location.replace('https://www.javascripttutorial.net');
}, 3000);
Code language: JavaScript (javascript)

reload()

The reload() method reloads the currently displayed page. When you call


the reload() method with no argument, the browser will reload the page in the most
efficient way e.g., it loads the page resources from the browser’s cache if they haven’t
changed since the last request.

reload();

To force a reload from the server, you pass true to the reload() method:

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

 The Location object represents the current URL of a page. It can be accessed


via window.location or document.location.
 The Location object has a number of properties that represent the URL such
as protocol, host, pathname, and search.
 To manipulate the location, you set its properties new values or use assign(), replace(),
and reload() methods.

How To Get Query String in JavaScript


Summary: in this tutorial, you will learn how to use the URLSearchParams  to get query
string parameters in JavaScript.

To get a query string you can access the search property of the location object:

location.search
Code language: CSS (css)

Assuming that the value of the location.search is:

'?type=list&page=20'
Code language: JavaScript (javascript)

To work with the query string, you can use the URLSearchParams object.

const urlParams = new URLSearchParams(location.search);


Code language: JavaScript (javascript)
The URLSearchParams is an iterable object, therefore you can use the for...of structure to
iterate over its elements which are query string parameters:

const urlParams = new URLSearchParams(location.search);

for (const [key, value] of urlParams) {


console.log(`${key}:${value}`);
}
Code language: JavaScript (javascript)

Output:

type:list
page:20
Code language: CSS (css)

Useful URLSearchParams methods

The URLSearchParams has some useful methods that return iterators of parameter keys,


values, and entries:

 keys() returns an iterator that iterates over the parameter keys.


 values() returns an iterator that iterates over the parameter values.
 entries() returns an iterator that iterates over the (key, value) pairs of the parameters.

keys() example

The following example uses the keys() method to list all parameter names of a query
string:

const urlParams = new URLSearchParams('?type=list&page=20');

for (const key of urlParams.keys()) {


console.log(key);
}
Code language: JavaScript (javascript)

Output:

type
page
values() example

The following example uses the keys() method to list all parameter values of a query
string:

const urlParams = new URLSearchParams('?type=list&page=20');

for (const value of urlParams.values()) {


console.log(value);
}
Code language: JavaScript (javascript)

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:

const urlParams = new URLSearchParams('?type=list&page=20');

for (const entry of urlParams.entries()) {


console.log(entry);
}
Code language: JavaScript (javascript)

Output:

["type", "list"]
["page", "20"]
Code language: JSON / JSON with Comments (json)

Check if a query string parameter exists

The URLSearchParams.has() method returns true if a parameter with a specified name exists.

const urlParams = new URLSearchParams('?type=list&page=20');

console.log(urlParams.has('type')); // true
console.log(urlParams.has('foo')); // false
Code language: JavaScript (javascript)
Output

true
false
Code language: JavaScript (javascript)

Summary

 The URLSearchParams provides an interface to work with query string parameters


 The URLSearchParams is an iterable so you can use the for...of construct to iterate over
query string parameters.
 The has() method of the URLSearchParams determines if a parameter with a specified name
exists.

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.

Redirect to a new URL

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)

Assigning a value to the href property of the location object has the same effect as calling


the assign() method of the location object:
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)

The following script redirects to contact.html page located the root folder:

location.href = '/contact.html';
Code language: JavaScript (javascript)

Redirect upon on page loading

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.

Was this tutorial helpful ?


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.

Redirect to a new URL

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)

Assigning a value to the href property of the location object has the same effect as calling


the assign() method of the location object:

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)

The following script redirects to contact.html page located the root folder:

location.href = '/contact.html';
Code language: JavaScript (javascript)

Redirect upon on page loading

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

 Navigator – query the information and capabilities of the browser using


the navigator object.

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)

In Google Chrome, you may see the following output:

"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36


(KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"
Code language: JSON / JSON with Comments (json)

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:

if( typeof window.addEventListener === 'function' ) {


// let's use addEventListener
} else {
// addEventListener is not supported, use another way
}
Code language: JavaScript (javascript)

JavaScript Navigator Properties & Methods

The following table illustrates the JavaScript Navigator properties and methods:

Property / Method Description

activeVrDisplays Returns an array of every VRDisplay instance with its presenting property is set


to true

appCodeName Returns “Mozilla” even in non-Mozilla browsers.

appName Returns the full browser name.

appVersion Returns the browser version. However, it typically does not correspond to the actual
version of the browser.

battery Returns a BatteryManager object to interact with the Battery status API

buildId Return the build number for the web browser.

connection Returns a NetworkInformation object to interact with the Network


information API

cookieEnabled Returns true if if cookies are enabled; otherwise false.

credentials Returns a CredentialsContainer to interact with the Credentials


Management API

deviceMemory Returns the amount of device memory in gigabytes.

doNotTrack Returns the user’s preference of do-not-track .

geolocation Returns a Geolocation object to interact with the Geolocation API.

getVRDisplays() Returns an array of every VRDisplay instance if available.

getUserMedia() Returns the stream associated with the available media device hardware.
Property / Method Description

hardwareConcurrency Returns the number of processor cores of the device

javaEnabled Determines if Java is enabled in the browser.

language Returns the browser’s primary language.

languages Returns an array of all the browser’s preferred languages.

locks Returns a LockManager object to interact with the Web Locks API.

mediaCapabilities Returns a MediaCapabilities object to interact with the Media capabilities API

mediaDevices Returns the available media devices.

maxTouchPoints Returns the maximum number of supported touch points for the device’s
touchscreen

mimeTypes Returns an array of MIME types registered with the browser.

onLine Specifies if the browser is connected to the Internet.

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.

platform Returns the system platform on which the browser is running.

plugins Returns an array of installed browser’s plug-ins.

product Returns the name of the product.

productSub Returns the extra information about the product.

registerProtocolHandler() Registers a website as a handler for a particular protocol.


Property / Method Description

requestMediaKeySystemAccess( Returns a Promise which resolves to a MediaKeySystemAccess object.


)

sendBeacon() Asynchronously transmits a small payload.

serviceWorker Returns the ServiceWorkerContainer used to interact with ServiceWorker object

share() Calls the current platform’s native sharing mechanism.

storage Returns the StorageManager object to interact with the Storage API.

userAgent Represents the user-agent string of the browser.

vendor Returns the brand name of the browser.

vendorSub Returns extra information about the browser’s vendor.

vibrate() Triggers the device to vibrate if vibration is supported.

webdriver Determines if the browser is currently controlled by automation.

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.

Introduction to the JavaScript Screen object

The Screen object provides the attributes of the screen on which the current window is
being rendered.

To access the Screen object, you use the screen property of the window object:

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

The window.screen object provides the following 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

height Represents the pixel height of the screen.

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.

top Represents the pixel distance of the current screen’s top.

width Represents the pixel width 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

height Represents the pixel height of the screen.

left Represents the pixel distance of the current screen’s left side.

pixelDepth A read-only that returns the bit depth of the screen.

top Represents the pixel distance of the current screen’s top.

width Represents the pixel width of the screen.

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.

Introduction to the JavaScript Screen object

The Screen object provides the attributes of the screen on which the current window is
being rendered.

To access the Screen object, you use the screen property of the window object:

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

The window.screen object provides the following 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.

height Represents the pixel height of the screen.

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.

top Represents the pixel distance of the current screen’s top.

width Represents the pixel width 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.

height Represents the pixel height of the screen.

left Represents the pixel distance of the current screen’s left side.

pixelDepth A read-only that returns the bit depth of the screen.

top Represents the pixel distance of the current screen’s top.


Property Description

width Represents the pixel width of the screen.

orientation  Returns the screen orientation as specified in the Screen Orientation API

Section 5. History

 History – manage the web browser’s history stack with the history object.

JavaScript History
Summary: in this tutorial, you will learn how to access the browser’s session history by
using the JavaScript history object.

Introduction to 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.

To manipulate the history stack, you use the history object which is a property of


the window object:

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

To move backward through history, you use the back() method:

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

Similarly, you can move forward by using the forward() method:

history.forward();
Code language: CSS (css)

It works like when you click the Forward button.

Move to a specific URL in the history

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.

For example, to move backward you use:

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)

To refresh the current page, you either pass 0 or no argument to the go() method:

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

 The window.history object allows you to access the history stack of the browser.


 To navigate to a URL in the history, you use the back(), forward(), and go() methods.
 The history.length returns the number of URLs in the history stack.

JavaScript DOM
Section 1. Getting started

 Understanding the Document Object Model in JavaScript

Document Object Model in JavaScript


Summary: in this tutorial, you will learn about the Document Object Model in
JavaScript.

What is Document Object Model (DOM)

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.

A document as a hierarchy of nodes

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)

The following tree represents the above HTML document:


In this DOM tree, the document is the root node. The root node has one child which is
the <html> element. The <html> element is called the document element.

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.

The following table illustrates the node type constants:

Constant Value Description

Node.ELEMENT_NODE 1 An Element node like <p> or <div>.

Node.TEXT_NODE 3 The actual Text inside an Element or Attr.

Node.CDATA_SECTION_NODE 4 A CDATASection, such as <!CDATA[[ … ]]>.

Node.PROCESSING_INSTRUCTION_NODE 7 A ProcessingInstruction of an XML document,


such as <?xml-stylesheet … ?>.

Node.COMMENT_NODE 8 A Comment node, such as <!-- … -->.

Node.DOCUMENT_NODE 9 A Document node.

Node.DOCUMENT_TYPE_NODE 10 A DocumentType node, such as <!DOCTYPE html>.

Node.DOCUMENT_FRAGMENT_NODE 11 A DocumentFragment node.

To get the type of a node, you use the nodeType property:

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

A node has two important properties: nodeName and nodeValue that provide specific


information about the node.

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)

Node and Element

Sometime, it’s easy to confuse between the Node and the Element.

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

An element is a node with a specific node type Node.ELEMENT_NODE, which is equal to 1.

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.

The following picture illustrates the relationship between the Node and Element types:


Note that the getElementById() and querySelector() returns an object with the Element type
while getElementsByTagName() or querySelectorAll() returns NodeList which is a collection of
nodes. 

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.

For example, <body> is a child node of the <html> node, and <html> is the parent of


the <body> node.

The <body> node is the sibling of the <head> node because they share the same


immediate parent, which is the <html> element.

The following picture illustrates the relationships between nodes:


Summary

 An HTML or XML document can be represented as a tree of nodes, like a traditional


family tree.
 Each markup can be represented as a node with a specific node type.
 Element is a specific type of node with the node type Node.ELEMENT_NODE.
 In the DOM tree, a node has relationships with other nodes.

Section 2. Selecting elements

 getElementById() – select an element by id.


 getElementsByName() – select elements by name.
 getElementsByTagName()  – select elements by a tag name.
 getElementsByClassName() – select elements by one or more class names.
 querySelector()  – select elements by CSS selectors.

JavaScript getElementById
Summary: in this tutorial, you will learn how to use the JavaScript getElementById() to
select an element by a specified id.

Introduction to JavaScript getElementById() method

An HTML element often has an id attribute like this:


<div id="root"></div>
Code language: HTML, XML (xml)

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.

The id is case-sensitive. For example, the 'root' and 'Root' are totally different id.

To select the element by its id, you use the document.getElementById method.

The following shows the syntax of the getElementById() method:

let element = document.getElementById(id);


Code language: JavaScript (javascript)

In this syntax, the id represents the id of the element that you want to select.

The getElementById() returns an Element object that describes the DOM element object with


the specified id. It returns null if there is no element with that id exists.

As mentioned earlier, id is unique within a document. However, HTML is a forgiving


language. If a document has more than one element with the same id,
the getElementById() method returns the first one it encounters.

JavaScript getElementById() method example

Consider the following HTML document:

<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

 The getElementById() returns a DOM element specified by an id or null if no matching


element found.
 If multiple elements share the same id, even though it is invalid,
the getElementById() returns the first element it encounters.

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.

Introduction to JavaScript getElementsByName() method

Every element on an HTML document may have a name attribute:

<input type="radio" name="language" value="JavaScript">


Code language: HTML, XML (xml)

Unlike the id attribute, multiple HTML elements can share the same value of


the name attribute like this:

<input type="radio" name="language" value="JavaScript">


<input type="radio" name="language" value="TypeScript">
Code language: HTML, XML (xml)

To get all elements with a specified name, you use the getElementsByName() method of


the document object:

let elements = document.getElementsByName(name);


Code language: JavaScript (javascript)

The getElementsByName() accepts a name which is the value of the name attribute of elements


and returns a live NodeList of elements.
The return collection of elements is live. It means that the return elements are
automatically updated when elements with the same name
are inserted and/or removed from the document.

JavaScript getElementsByName() example

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:

 First, select the Rate button by its id btnRate using the getElementById() method.


 Second, hook a click event to the Rate button so that when the button is clicked, an
anonymous function is executed.
 Third, call the getElementsByName() in the click event handler to select all radio buttons that
have the name rate.
 Finally, iterate over the radio buttons. If a radio button is checked, then display
an alert that shows the value of the selected radio button.

Notice that you will learn about events like click later. For now, you just need to focus on
the getElementsByName() method.

Summary

 The getElementsByName() returns a live NodeList of elements with a specified name.


 The NodeList is an array-like object, not an array object.

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.

To create an HTML element, you use the document.createElement() method:

let element = document.createElement(htmlTag);


Code language: JavaScript (javascript)
The document.createElement() accepts an HTML tag name and returns a new Node with
the Element type.

1) Creating a new div example

Suppose that you have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS CreateElement Demo</title>
</head>
<body>

</body>
</html>
Code language: HTML, XML (xml)

The following example uses the document.createElement() to create a new <div> element:

let div = document.createElement('div');


Code language: JavaScript (javascript)

And add an HTML snippet to the div:

div.innerHTML = '<p>CreateElement example</p>';


Code language: HTML, XML (xml)

To attach the div to the document, you use the appendChild() method:

document.body.appendChild(div);
Code language: CSS (css)

Put it all together:

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

Adding an id to the div

If you want to add an id to a div, you set the id attribute of the element to a value, like
this:

let div = document.createElement('div');


div.id = 'content';
div.innerHTML = '<p>CreateElement example</p>';

document.body.appendChild(div);
Code language: JavaScript (javascript)

Adding a class to the div

The following example set the CSS class of a new div note:

let div = document.createElement('div');


div.id = 'content';
div.className = 'note';
div.innerHTML = '<p>CreateElement example</p>';

document.body.appendChild(div);
Code language: JavaScript (javascript)

Adding text to a div

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:

// create a new div and set its attributes


let div = document.createElement('div');
div.id = 'content';
div.className = 'note';

// create a new text node and add it to the div


let text = document.createTextNode('CreateElement example');
div.appendChild(text);

// add div to the document


document.body.appendChild(div);
Code language: JavaScript (javascript)

Adding an element to a div

To add an element to a div, you create an element and append it to the div using


the appendChild() method:

let div = document.createElement('div');


div.id = 'content';
div.className = 'note';

// create a new heading and add it to the div


let h2 = document.createElement('h2');
h2.textContent = 'Add h2 element to the div';
div.appendChild(h2);

// add div to the document


document.body.appendChild(div);
Code language: JavaScript (javascript)

2) Creating new list items ( li) example

Let’s say you have a list of items:

<ul id="menu">
<li>Home</li>
</ul>
Code language: HTML, XML (xml)

The following code adds two li elements to the ul:

let li = document.createElement('li');
li.textContent = 'Products';
menu.appendChild(li);

li = document.createElement('li');
li.textContent = 'About Us';

// select the ul menu element


const menu = document.querySelector('#menu');
menu.appendChild(li);
Code language: JavaScript (javascript)

Output:

<ul id="menu">
<li>Home</li>
<li>Products</li>
<li>About Us</li>
</ul>
Code language: HTML, XML (xml)

3) Creating a script element example

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.

The following example illustrates how to create a new script element and loads


the /lib.js file to the document:

let script = document.createElement('script');


script.src = '/lib.js';
document.body.appendChild(script);
Code language: JavaScript (javascript)

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)

And then use the helper function to load the /lib.js file:

loadJS('/lib.js');
Code language: JavaScript (javascript)

To load a JavaScript file asynchronously, you set the async attribute of the script element


to true:

function loadJSAsync(url) {
let script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
}
Code language: JavaScript (javascript)

Summary

 The document.createElement() creates a new HTML element.


 The element.appendChild() appends an HTML element to an existing element.

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.

Introduction to the JavaScript appendChild() method

The appendChild() is a method of the Node interface. The appendChild() method allows you to


add a node to the end of the list of child nodes of a specified parent node.

The following illustrates the syntax of the appendChild() method:

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.

If the childNode is a reference to an existing node in the document,


the appendChild() method moves the childNode from its current position to the new position.

JavaScript appendChild() examples

Let’s take some examples of using the appendChild() method.

1) Simple appendChild() example

Suppose that you have the following HTML markup:

<ul id="menu">
</ul>
Code language: HTML, XML (xml)

The following example uses the appendChild() method to add three list items to


the <ul> element:

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)

Put it all together:

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

2) Moving a node within the document example

Assuming that you have two lists of items:

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

// get the first list


const firstList = document.querySelector('#first-list');
// take the first child element
const everest = firstList.firstElementChild;
// get the second list
const secondList = document.querySelector('#second-list');
// append the everest to the second list
secondList.appendChild(everest)
Code language: JavaScript (javascript)

How it works:

 First, select the first element by its id (first-list) using the querySelector() method.


 Second, select the first child element from the first list.
 Third, select the second element by its id (second-list) using the querySelector() method.
 Finally, append the first child element from the first list to the second list using
the appendChild() method.
Here are the list before and after moving:

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:

let text = node.textContent;


Code language: JavaScript (javascript)

Suppose that you have the following HTML snippet:

<div id="note">
JavaScript textContent Demo!
<span style="display:none">Hidden Text!</span>
<!-- my comment -->
</div>
Code language: HTML, XML (xml)

The following example uses the textContent property to get the text of the <div> element:

let note = document.getElementById('note');


console.log(note.textContent);
Code language: JavaScript (javascript)

How it works.

 First, select the div element with the id note by using the getElementById() method.


 Then, display the text of the node by accessing the textContent property.

Output:

JavaScript textContent Demo!


Hidden Text!

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:

let note = document.getElementById('note');


console.log(note.innerText);
Code language: JavaScript (javascript)

Output:

JavaScript textContent Demo!

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:

let note = document.getElementById('note');


note.textContent = 'This is a note';
Code language: JavaScript (javascript)

Summary

 Use the textContent property to return the concatenation of the textContent of every child


node. You can use it to set a text for a node.
 The innerText returns the human-readable text that takes CSS into account.

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.

Reading the innerHTML property of an element

To get the HTML markup contained within an element, you use the following syntax:

let content = element.innerHTML;


Code language: JavaScript (javascript)

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

Suppose that you have the following markup:

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

let menu = document.getElementById('menu');


console.log(menu.innerHTML);
Code language: JavaScript (javascript)

How it works:

 First, select the <ul> element by its id (menu) using the getElementById() method.


 Then, get the HTML content of the <ul> element using the innerHTML.

Output:

<li>Home</li>
<li>Services</li>
Code language: HTML, XML (xml)

2) Examining the current HTML source

The innerHTML property returns the current HTML source of the document, including all
changes have been made since the page was loaded.

See the following example:

<!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');

// create new li element


let li = document.createElement('li');
li.textContent = 'About Us';
// add it to the ul element
menu.appendChild(li);

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.

 First, get the <ul> element with the id menu using the getElementById() method.


 Second, create a new <li> element and add it to the <ul> element using
the createElement() and appendChild() methods.
 Third, get the HTML of the <ul> element using the innerHTML property of
the <ul> element. The contents of the <ul> element includes the initial content and the
dynamic content created by JavaScript.

Setting the innerHTML property of an element

To set the value of innerHTML property, you use this syntax:

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

const main = document.getElementById('main');

const scriptHTML = '<script>alert("Alert from


innerHTML");</script>';
main.innerHTML = scriptHTML;
Code language: JavaScript (javascript)

In this example, the alert() inside the <script> tag will not execute.

However, if you change source code of the app.js to the following:

const main = document.getElementById('main');

const externalHTML = `<img src='1' onerror='alert("Error loading


image")'>`;
// shows the alert
main.innerHTML = externalHTML;
Code language: JavaScript (javascript)

The alert() will show because the image cannot be loaded successfully. It causes


the onerror handler executes. And this handler can execute any malicious code, not just a
simple alert.

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

 Use innerHTML property of an element to get or set HTML contained within the element.


 The innerHTML property returns the current HTML source of the element, including any
change that has been made since the page was loaded.
 Do not use innerHTML to set new content that you have no control over to avoid a
security risk.

JavaScript innerHTML vs createElement


Summary: in this tutorial, you’ll learn the difference between
the innerHTML and createElement() when it comes to creating new elements in the DOM tree.

#1) createElement is more performant

Suppose that you have a div element with the class container:

<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 div = document.querySelector('.container');

let p = document.createElement('p');
p.textContent = 'JS DOM';
div.appendChild(p);
Code language: JavaScript (javascript)

You can also manipulate an element’s HTML directly using innerHTML like this:

let div = document.querySelector('.container');


div.innerHTML += '<p>JS DOM</p>';
Code language: JavaScript (javascript)

Using innerHTML is cleaner and shorter when you want to add attributes to the element:

let div = document.querySelector('.container');


div.innerHTML += '<p class="note">JS DOM</p>';
Code language: JavaScript (javascript)

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.

#2) createElement is more secure

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.

#3) Using DocumentFragment for composing DOM Nodes

Assuming that you have a list of elements and you need in each iteration:

let div = document.querySelector('.container');

for (let i = 0; i < 1000; i++) {


let p = document.createElement('p');
p.textContent = `Paragraph ${i}`;
div.appendChild(p);
}
Code language: JavaScript (javascript)

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:

let div = document.querySelector('.container');

// compose DOM nodes


let fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
let p = document.createElement('p');
p.textContent = `Paragraph ${i}`;
fragment.appendChild(p);
}

// append the fragment to the DOM tree


div.appendChild(fragment);
Code language: JavaScript (javascript)
In this example, we composed the DOM nodes by using the DocumentFragment object and
append the fragment to the active DOM tree once at the end.

A document fragment does not link to the active DOM tree, therefore, it doesn’t incur
any performance.

Check it out the DocumentFragment tutorial for more detail.

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.

Introduction to the JavaScript DocumentFragment interface

The DocumentFragment interface is a lightweight version of the Document that stores a piece


of document structure like a standard document. However, a DocumentFragment isn’t part of
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.

To create a new document fragment, you use the DocumentFragment constructor like this:

let fragment = new DocumentFragment();


Code language: JavaScript (javascript)

Or you can use the createDocumentFragment() method of the Document object:

let fragment = document.createDocumentFragment();


Code language: JavaScript (javascript)

This DocumentFragment inherits the methods of its parent, Node, and also implements those


of the ParentNode interface such as querySelector() and querySelectorAll().
JavaScript DocumentFragment example

Suppose that you have a <ul> element with the id language:

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

let languages = ['JS', 'TypeScript', 'Elm', 'Dart','Scala'];

let langEl = document.querySelector('#language')

let fragment = new DocumentFragment();


languages.forEach((language) => {
let li = document.createElement('li');
li.innerHTML = language;
fragment.appendChild(li);
})

langEl.appendChild(fragment);
Code language: JavaScript (javascript)
How it works:

 First, select the <ul> element by its id using the querySelector() method.


 Second, create a new document fragment.
 Third, for each element in the languages array, create a list item element, assign the list
item’s innerHTML to the language, and append all the newly created list items to the
document fragment.
 Finally, append the document fragment to the <ul> element.

Put it all together:

<!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'];

let langEl = document.querySelector('#language');


let fragment = new DocumentFragment();

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:

 The newNode is the new node to be inserted.


 The existingNode is the node before which the new node is inserted. If
the existingNode is null, the insertBefore() inserts the newNode at the end of the parentNode‘s
child nodes.

The insertBefore() returns the inserted child node.

JavaScript insertBefore() helper function

The following insertBefore() function inserts a new node before a specified node:

function insertBefore(newNode, existingNode) {


existingNode.parentNode.insertBefore(newNode, existingNode);
}
Code language: JavaScript (javascript)
JavaScript insertBefore() example

Suppose that you have the following list of items:

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

let menu = document.getElementById('menu');


// create a new li node
let li = document.createElement('li');
li.textContent = 'Home';

// insert a new node before the first list item


menu.insertBefore(li, menu.firstElementChild);
Code language: JavaScript (javascript)

How it works.

 First, get the menu element using the getElementById() method.


 Second, create a new list item using the createElement() method.
 Third, insert the list item element before the first child element of the menu element using
the insertBefore() method.

Put it all together.

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

// insert a new node before the first list item


menu.insertBefore(li, menu.firstElementChild);
</script>
</body>

</html>
Code language: HTML, XML (xml)

Summary

 Use the parentNode.insertBefore() to insert a new node before an existing node as a child


node of a parent node.

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:

 First, select the next sibling node of the existing node.


 Then, select the parent node of the existing node and call the insertBefore() method on
the parent node to insert a new node before that immediate sibling node.

The following insertAfter() function illustrates the logic:

function insertAfter(newNode, existingNode) {


existingNode.parentNode.insertBefore(newNode,
existingNode.nextSibling);
}
Code language: JavaScript (javascript)

Suppose that you have the following list of items:


<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
Code language: HTML, XML (xml)

The following snippet inserts a new node after the first list item:

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);
Code language: JavaScript (javascript)

How it works:

 First, select the ul element by its id (menu) using the getElementById() method.


 Second, create a new list item using the createElement() method.
 Third, use the insertBefore() method to insert the list item element before the next sibling
of the first list item element.

Put it all together.

<!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 DOM hasn’t supported the insertAfter() method yet.


 Use the insertBefore() method and the nextSibling property to insert a new before an
existing node as a child of a parent node.

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

The parentNode.append() method inserts 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)

The append() method will insert DOMString objects as Text nodes.

Note that a DOMString is a UTF-16 string that maps directly to a string.

The append() method has no return value. It means that the append() method implicitly


returns undefined.

JavaScript append() method examples

Let’s take some examples of using the append() method.


1) Using the append() method to append an element example

Suppose that you have the following ul element:

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

let app = document.querySelector('#app');

let langs = ['TypeScript','HTML','CSS'];

let nodes = langs.map(lang => {


let li = document.createElement('li');
li.textContent = lang;
return li;
});

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:

 First, select the ul element by its id by using the querySelector() method.


 Second, declare an array of languages.
 Third, for each language, create a new li element with the textContent is assigned to the
language.
 Finally, append li elements to the ul element by using the append() method.

2) Using the append() method to append text to an element example

Assume that you have the following HTML:


<div id="app"></div>
Code language: HTML, XML (xml)

You can use the append() method to append a text to an element:

let app = document.querySelector('#app');


app.append('append() Text Demo');

console.log(app.textContent);
Code language: JavaScript (javascript)

Output HTML:

<div id="app">append() Text Demo</div>


Code language: HTML, XML (xml)

append vs. appendChild()

Here are the differences between append() and appendChild():

Differences append() appendChild()

Return value undefined The appended Node object

Input Multiple Node Objects A single Node object

Parameter Types Accept Node and DOMString Only Node

Summary

 Use the parentNode.append() method to append a set of Node objects or DOMString objects


after the last child node of the parentNode.

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

The parentNode.append() method inserts 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)

The append() method will insert DOMString objects as Text nodes.

Note that a DOMString is a UTF-16 string that maps directly to a string.

The append() method has no return value. It means that the append() method implicitly


returns undefined.

JavaScript append() method examples

Let’s take some examples of using the append() method.

1) Using the append() method to append an element example

Suppose that you have the following ul element:

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

let app = document.querySelector('#app');

let langs = ['TypeScript','HTML','CSS'];

let nodes = langs.map(lang => {


let li = document.createElement('li');
li.textContent = lang;
return li;
});

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:

 First, select the ul element by its id by using the querySelector() method.


 Second, declare an array of languages.
 Third, for each language, create a new li element with the textContent is assigned to the
language.
 Finally, append li elements to the ul element by using the append() method.

2) Using the append() method to append text to an element example

Assume that you have the following HTML:

<div id="app"></div>
Code language: HTML, XML (xml)

You can use the append() method to append a text to an element:

let app = document.querySelector('#app');


app.append('append() Text Demo');

console.log(app.textContent);
Code language: JavaScript (javascript)

Output HTML:

<div id="app">append() Text Demo</div>


Code language: HTML, XML (xml)

append vs. appendChild()

Here are the differences between append() and appendChild():

Differences append() appendChild()

Return value undefined The appended Node object


Input Multiple Node Objects A single Node object

Parameter Types Accept Node and DOMString Only Node

Summary

 Use the parentNode.append() method to append a set of Node objects or DOMString objects


after the last child node of the parentNode.

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.

Introduction to JavaScript prepend() method

The prepend() method inserts a set of Node objects or DOMString objects after the first child


of a parent node:

parentNode.prepend(...nodes);

parentNode.prepend(...DOMStrings);
Code language: JavaScript (javascript)

The prepend() method inserts DOMString objects as Text nodes. Note that a DOMString is a


UTF-16 string that directly maps to a string.

The prepend() method returns undefined.

JavaScript prepend() method examples

Let’s take some examples of using the prepend() method.

1) Using the prepend() method to prepend an element example

Let’s say you have the following ul element:

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

let app = document.querySelector('#app');

let langs = ['CSS','JavaScript','TypeScript'];

let nodes = langs.map(lang => {


let li = document.createElement('li');
li.textContent = lang;
return li;
});

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:

 First, select the ul element by its id by using the querySelector() method.


 Second, declare an array of strings.
 Third, for each element in an array, create a new li element with the textContent is assigned
to the array element.
 Finally, prepend the li elements to the ul parent element by using the prepend() method.

2) Using the prepend() method to prepend text to an element example

Suppose that you have the following element:

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

let app = document.querySelector('#app');


app.prepend('prepend() Text Demo');

console.log(app.textContent);
Code language: JavaScript (javascript)

Output HTML:

<div id="app">prepend() Text Demo</div>


Code language: HTML, XML (xml)

Summary

 Use the parentNode.prepend() method to prepend a list of Node objects or DOMString objects


before the first child node of the parent node.

JavaScript insertAdjacentHTML
Summary: in this tutorial, you’ll learn how to use the insertAdjacentHTML() method to insert
HTML into the document.

Introduction to JavaScript insertAdjacentHTML() method

The insertAdjacentHTML() is a method of the Element interface so that you can invoke it from


any element.

The insertAdjacentHTML() method parses a piece of HTML text and inserts the resulting


nodes into the DOM tree at a specified position:

element.insertAdjacentHTML(positionName, text);
Code language: JavaScript (javascript)

The insertAdjacentHTML() method has two parameters:

1) position

The positionName is a string that represents the position relative to the element.


The positionName accepts one of the following four values:

 'beforebegin': before the element


 'afterbegin': before its first child of the element.
 'beforeend': after the last child of the element
 'afterend': after the element

Note that the 'beforebegin' and 'afterend' are only relevant if the element is in the DOM tree
and has a parent element.

The insertAdjacentHTML() method has no return value, or undefined by default.

The following visualization illustrates the position name:

2) text

The text parameter is a string that the insertAdjacentHTML() method parses as HTML or XML.


It cannot be Node objects

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.

JavaScript insertAdjacentHTML() method example

The following JavaScript example uses the insertAdjacentHTML() method to insert various


elements into the page with the positions relative to the ul element:

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

 First, select the ul element by its id list using the querySelector() method.


 Next, use the insertAdjacentHTML() method to insert a heading 2 element before
the ul element. The position is 'beforebegin'.
 Then, use the insertAdjacentHTML() method to insert a new list item element before the
first child of the ul element. The position is 'afterbegin'.
 After that, use the insertAdjacentHTML() method to insert a new list item element after the
last child of the ul element with the position 'beforeend'.
 Finally, insert use the insertAdjacentHTML() method to insert a new paragraph element
after the ul element with the position 'afterend'.

Summary

 Use the insertAdjacentHTML() method to insert a text as Nodes into the DOM tree at a


specified position.
 Always escape the user input text that you pass into the insertAdjacentHTML() method to
avoid security risk.

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.

To replace an HTML element, you use the node.replaceChild() method:

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.

Suppose that you have the following list of items:

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

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

 Use Node.replaceChild() to replace a child element of a node by a new element.

JavaScript cloneNode
Summary: in this tutorial, you will learn how to use the JavaScript cloneNode() method to
clone an element.

The cloneNode() is a method of the Node interface that allows you to clone an element:

let clonedNode = originalNode.cloneNode(deep);


Code language: JavaScript (javascript)
Pamaraters

deep

The cloneNode() method accepts an optional parameter 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.

The deep parameter defaults to false if you omit it.

originalNode

The originalNode is the element to be cloned.

Return value

The cloneNode() returns a copy of the originalNode.

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

The following example uses the cloneNode() method to copy the <ul> element and place it


in the same document:

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

 First, select the <ul> with the id menu by using the querySelector() method.


 Second, create a deep clone of the <ul> element using the cloneNode() method.
 Third, change the id of the cloned element to avoid duplicate.
 Finally, append the cloned element to the child nodes of the document.body using
the appendChild() method.
Summary

 Use the node.cloneNode() method to clone the node.


 Pass true into the cloneNode() method to create a deep clone of a DOM element.

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

To remove a child element of a node, you use the removeChild() method:

let childNode = parentNode.removeChild(childNode);


Code language: JavaScript (javascript)

The childNode is the child node of the parentNode that you want to remove. If the childNode is


not the child node of the parentNode, the method throws an exception.
The removeChild() returns the removed child node from the DOM tree but keeps it in the
memory, which can be used later.

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

Suppose you have the following list of items:

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

let menu = document.getElementById('menu');


menu.removeChild(menu.lastElementChild);
Code language: JavaScript (javascript)

How it works:

 First, get the ul element with the id menu by using the getElementById() method.


 Then, remove the last element of the ul element by using the removeChild() method.
The menu.lastElementChild property returns the last child element of the menu.

Put it all together.

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

Removing all child nodes of an element

To remove all child nodes of an element, you use the following steps:

 Get the first node of the element using the firstChild property.


 Repeatedly removing the child node until there are no child nodes left.

The following code shows how to remove all list items of the menu element:

let menu = document.getElementById('menu');


while (menu.firstChild) {
menu.removeChild(menu.firstChild);
}
Code language: JavaScript (javascript)

You can remove all child nodes of an element by setting the innerHTML property of the
parent node to blank:

let menu = document.getElementById('menu');


menu.innerHTML = '';
Code language: JavaScript (javascript)

Summary

 Use parentNode.removeChild() to remove a child node of a parent node.


 The parentNode.removeChild() throws an exception if the child node cannot be found in the
parent node.

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.

Suppose you have a button with the id btn:

<button id="btn">Click Me!</button>


Code language: HTML, XML (xml)

To define the code that will be executed when the button is clicked, you need to register
an event handler using the addEventListener() method:

let btn = document.querySelector('#btn');

function display() {
alert('It was clicked!');
}

btn.addEventListener('click',display);
Code language: JavaScript (javascript)

How it works.

 First, select the button with the id btn by using the querySelector() method.


 Then, define a function called display() as an event handler.
 Finally, register an event handler using the addEventListener() so that when users click the
button, the display() function will be executed.

A shorter way to register an event handler is to place all code in an anonymous function,
like this:

let btn = document.querySelector('#btn');

btn.addEventListener('click',function() {
alert('It was clicked!');
});
Code language: JavaScript (javascript)

Event flow

Assuming that you have the following HTML document:

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

Note that modern


web browsers bubble the event up to the window object.

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

The following picture illustrates the event capturing effect:


DOM Level 2 Event flow

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:

let btn = document.querySelector('#btn');

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

bubbles true if the event bubbles

cancelable true if the default behavior of the event can be canceled

currentTarget the current element on which the event is firing

defaultPrevented return true if the preventDefault() has been called.

detail more informatio nabout the event

eventPhase 1 for capturing phase, 2 for target, 3 for bubbling

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.

target the target element of the event

type the type of event that was fired

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

To prevent the default behavior of an event, you use the preventDefault() method.

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)

However, you can prevent this behavior by using the preventDefault() method of


the event object:

let link = document.querySelector('a');

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

The stopPropagation() method immediately stops the flow of an event through the DOM


tree. However, it does not stop the browers default behavior.

See the following example:

let btn = document.querySelector('#btn');

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)

Without the stopPropagation() method, you would see two messages on the Console


window.

However, the click event never reaches the body because the stopPropagation() was called on


the click event handler of the button.

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.

You might also like