0% found this document useful (0 votes)
36 views

Js Summary

Uploaded by

Abshir Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Js Summary

Uploaded by

Abshir Ahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

DOM (Document Object Model)

Last Updated : 01 Mar, 2024



HTML DOM, allows JavaScript to access and modify all the elements in an HTML document.

In this article, we will discuss DOM along with its properties and methods used to manipulate
documents and understand their implementation through the examples.

Note: It is called a Logical structure because DOM doesn’t specify any relationship between
objects.

Table of Content

• Why DOM is required?


• Structure of DOM
• Properties of DOM
• Methods of Document Object Model
• What DOM is not?
• Levels of DOM:

What is DOM?
The Document Object Model (DOM) is a programming interface for HTML(HyperText
Markup Language) and XML(Extensible Markup Language) documents. It defines the logical
structure of documents and the way a document is accessed and manipulated.

So basically Document Object Model is an API that represents and interacts with HTML or
XML documents.

The DOM is a W3C (World Wide Web Consortium) standard and it defines a standard for
accessing documents.

The W3C Dom standard is divided into three different parts:

• Core DOM – standard model for all document types

• XML DOM – standard model for XML documents

• HTML DOM – standard model for HTML documents


HTML DOM
HTML DOM is a standard object model and programming interface for HTML documents.
HTML DOM is a way to represent the webpage in a structured hierarchical way so that it will
become easier for programmers and users to glide through the document.

With HTML DOM, we can easily access and manipulate tags, IDs, classes, attributes, or elements
of HTML using commands or methods provided by the document object.

Using DOM JavaScript we get access to HTML as well as CSS of the web page and can also
modify the behavior of the HTML elements.

Why is DOM Required?


HTML is used to structure the web pages and Javascript is used to add behavior to our web
pages. When an HTML file is loaded into the browser, the JavaScript can not understand the
HTML document directly. So it interprets and interacts with the Document Object Model (DOM),
which is created by the browser based on the HTML document.

DOM is basically the representation of the same HTML document but in a tree-like structure
composed of objects. JavaScript can not understand the tags(<h1>H</h1>) in HTML document
but can understand object h1 in DOM.

JavaScript interprets DOM easily, using it as a bridge to access and manipulate the elements. DOM
Javascript allow access to each of the objects (h1, p, etc) by using different functions.

The Document Object Model (DOM) is essential in web development for several
reasons:

• Dynamic Web Pages: It allows you to create dynamic web pages. It enables the
JavaScript to access and manipulate page content, structure, and style dynamically which
gives interactive and responsive web experiences, such as updating content without
reloading the entire page or responding to user actions instantly.

• Interactivity: With the DOM, you can respond to user actions (like clicks, inputs, or
scrolls) and modify the web page accordingly.

• Content Updates: When you want to update the content without refreshing the entire
page, the DOM enables targeted changes making the web applications more efficient and
user-friendly.

• Cross-Browser Compatibility: Different browsers may render HTML and CSS in


different ways. The DOM provides a standardized way to interact with page elements.
• Single-Page Applications (SPAs): Applications built with frameworks such as React or
Angular, heavily rely on the DOM for efficient rendering and updating of content within
a single HTML page without reloading the full page.

Structure of DOM
DOM can be thought of as a Tree or Forest (more than one tree). The term structure model is
sometimes used to describe the tree-like representation of a document.

Each branch of the tree ends in a node, and each node contains objects Event listeners can be
added to nodes and triggered on an occurrence of a given event. One important property of DOM
structure models is structural isomorphism: if any two DOM implementations are used to create
a representation of the same document, they will create the same structure model, with precisely
the same objects and relationships.

Why DOM is called an Object Model?

Documents are modeled using objects, and the model includes not only the structure of a document
but also the behavior of a document and the objects of which it is composed like tag elements with
attributes in HTML.

Properties of DOM
Let’s see the properties of the document object that can be accessed and modified by the
document object.
Representation of the DOM

• Window Object: Window Object is object of the browser which is always at top of the
hierarchy. It is like an API that is used to set and access all the properties and methods of
the browser. It is automatically created by the browser.

• Document object: When an HTML document is loaded into a window, it becomes a


document object. The ‘document’ object has various properties that refer to other objects
which allow access to and modification of the content of the web page. If there is a need
to access any element in an HTML page, we always start with accessing the ‘document’
object. Document object is property of window object.

• Form Object: It is represented by form tags.

• Link Object: It is represented by link tags.

• Anchor Object: It is represented by a href tags.

• Form Control Elements: Form can have many control elements such as text fields,
buttons, radio buttons, checkboxes, etc.

Methods of Document Object


DOM provides various methods that allows users to interact with and manipulate the document.
Some commonly used DOM methods are:

• write(“string”): Writes the given string on the document.

• getElementById(): returns the element having the given id value.

• getElementsByName(): returns all the elements having the given name value.

• getElementsByTagName(): returns all the elements having the given tag name.

• getElementsByClassName(): returns all the elements having the given class name.

In modern web development, having a way to persist data helps developers improve performance
and create a better user experience. And using local storage is an effective way of persisting data
in an application.

In this article, you will learn what local storage is and how to use it in modern web applications.
You will also learn the advantages of using local storage, as well as some of its limitations.

Table of Contents
• What is Local Storage?
• Differences Between Local Storage and Session Storage
• How to Use Local Storage
• A Practical Example
• How to View Local Storage in DevTools
• Benefits of Using Local Storage
• Limitations of Local Storage
• Conclusion

What is Local Storage?


Local storage is a feature in web browsers that allows developers to save data in the user’s
browser. It’s part of the web storage API, together with session storage.

Local storage works by accepting data in key-value pairs. It retains the data even when the user
refreshes the page or closes the tab or browser.

Differences Between Local Storage and Session Storage


As I mentioned earlier, the web storage API in modern browsers provides two main features for
data storage. These are local storage and session storage.

The key differences between the two are the lifespan of the stored data and their scope.

Data in local storage remains available even when the tab/browser is closed. But closing the
tab/browser clears any data stored in session storage.

Also, data in local storage is accessible across multiple browser tabs and windows. On the other
hand, data in session storage is only accessible within specific browser tabs and is not shared.

How to Use Local Storage


The local storage object provides different methods you can use to interact with it. With these
methods, you can add, read, and delete data from local storage.

How to Store Data in Local Storage

To store data in local storage, you use the setItem() method. This method takes in two
arguments, a key and a value.

localStorage.setItem(key, value)

If the key does not exist in local storage, the setItem() method will create a new key and assign
the given value to it. But if a key with the same name exists in local storage, it will update the
value of the key with the provided value.
How to Read Data From Local Storage

To retrieve and use data from local storage, you use the getItem() method. This method takes
in a key as an argument.

localStorage.getItem(key)

If the given key exists in local storage, the method returns the value of that key. If it doesn’t, the
method returns null.

How to Store and Read Complex Data Values in Local Storage

Local storage can only store strings. This means if you need to store values like objects or arrays,
you first need to get a string representation of the value. You do this using the
JSON.stringify() method.

Example:

const userObj = {
username = "Maria",
email: "[email protected]"
}

localStorage.setItem('user', JSON.stringify(userObj))

The JSON.stringify() method converts the userObj object into a string representation before
sending it to local storage.

Now, when you want to retrieve the data back from local storage, you also need to change it
from its string representation back to the original form. And you do that using the JSON.parse()
method.

Example:

const storedUserData = localStorage.getItem('user')

if (storedUserData) {
const userData = JSON.parse(storedUserData)
// You can use userData here...
} else {
console.log('User data not found in local storage')
}

In the example above, we first check if there is data for ‘user’ in local storage before using the
JSON.parse() method. This is important because if it does not exist in local storage,
JSON.parse() will be applied to a null value (which will result in an error).

How to Delete Data from Local Storage


There are two methods available for deleting data from local storage. One is the removeItem()
method and the other is the clear() method.

You use the removeItem() method when you want to delete a single item from local storage.
The method takes in a key as an argument and deletes the corresponding key-value pair from
local storage.

localStorage.removeItem(key)

But what if, instead of deleting a single key-value pair, you want to clear all data from the local
storage? Well, local storage has a method for that - the clear() method.

localStorage.clear()

The clear() method deletes all key-value pairs in the local storage for the current domain.

How to Get the Name of a Key in Local Storage

If you want to get the name of a key at a particular index in local storage, you can use the key()
method. It takes in a number as an argument and returns the name of the key at that specified
index.

Example:

localStorage.key(0)

The example above will return the name of the key at index 0. If there is no key at the specified
index, the method will return null.

A Practical Example
The following shows a practical demo of the difference between local storage and session
storage.

In this example, we'll save the user's name in local storage and save the age in session storage.

<!-- HTML -->


<body>

<h1 class="userName"></h1>
<h2 class="userAge"></h2>

<input type="text" class="name" placeholder="Enter name here"/>


<button class="saveNameBtn">Save Name</button>

<br />

<input type="text" class="age" placeholder="Enter age here"/>


<button class="saveAgeBtn">Save Age</button>

</body>

The markup includes two header elements. One for userName and the other for userAge. It also
includes two input elements for name and age. Each input has an associated button we'll use for
saving the data.

Now, let's use the querySelector method to select the various elements.

const userNameText = document.querySelector(".userName")


const userAgeText = document.querySelector(".userAge")

const saveNameButton = document.querySelector(".saveNameBtn")


const saveAgeButton = document.querySelector(".saveAgeBtn")

Code Example for Local Storage


saveNameButton.addEventListener("click", () => {
const userName = document.querySelector(".name").value
userNameText.textContent = userName
localStorage.setItem("name", userName)
})

First, we get the value of the name input, set it as the textContent of userNameText. And then
use the setItem() of local storage to save the userName value in local storage.

Next, let's see how we can get the name value from local storage when we need it.

function displayUserName () {
const nameFromLocalStorage = localStorage.getItem("name")

if (nameFromLocalStorage) {
userNameText.textContent = nameFromLocalStorage
} else {
userNameText.textContent = "No name data in local storage"
}
}

displayUserName()

The displayUserName function gets nameFromLocalStorage using the getItem() method. If


the value exists in local storage, we set it as the textContent of the userNameText element. If
it's null or doesn't exist, then we set textContent to the string "No name data in local storage".

Code Example for Session Storage

Now, let's do the same thing for the age value. The only difference here will be using session
storage instead of local storage.
saveAgeButton.addEventListener("click", () => {
const userAge = document.querySelector(".age").value
userAgeText.textContent = userAge
sessionStorage.setItem("age", userAge)
})

function displayUserAge () {
const ageFromSessionStorage = sessionStorage.getItem("age")

if (ageFromSessionStorage) {
userAgeText.textContent = ageFromSessionStorage
} else {
userAgeText.textContent = "No age data in session storage"
}
}

displayUserAge()

The setItem and getItem methods also works for session storage.

Demo:

Local storage and session storage demo.

As you can see from the demo above, when you close and reopen the page, the name data from
local storage persists. But the age data from session storage is cleared once the page closes.

Try your hands on the code sample on StackBlitz

How to View Local Storage in DevTools


You can follow the steps below to inspect the contents of local storage in your browser's
developer tools.

First, open DevTools. You can do that by right clicking on the web page and selecting "Inspect".

Demo of how to open the DevTools.

Then, select the "Application" tab on the DevTools panel. Depending on your browser, this panel
may have a different name. For example, it's called "Storage" in Safari and Firefox.
Demo of how to open the "Application" panel in DevTools.

Locate the "Storage" section on the sidebar showing a list of the various web storage options.

Click on "Local Storage" to expand and view its contents.

Demo of how to open the local storage tab in the storage panel.

You can click on individual items to view the corresponding key-value pair.
Benefits of Using Local Storage
The following are some of the benefits local storage has over other storage mechanisms in
modern web development.

1. Persistent data: When you use local storage, the stored data remains even when the user
closes the tab or the browser. This is useful for saving user preferences, settings, and
other relevant data. It can help create a seamless user experience.
2. Offline access: You can use local storage as a means to cache data which can be
accessed even with limited or no internet. This makes it a useful feature for apps that rely
on caching data for offline use like news readers, productivity apps, and so on.
3. More storage capacity: Compared to other storage means, local storage has a relatively
high capacity. For example, cookies are limited to 4 kilobytes per domain. But local
storage can store up to 5 megabytes of data per domain.

Limitations of Using Local Storage


1. Stores only strings: As you learned earlier, local storage can only store string values.
You can use the JSON stringify and parse methods to work around it. But some web
developers may not prefer it as it can lead to writing complex code that’s difficult to
debug.
2. Security concerns: Data in the local storage can be prone to attacks like cross-site
scripting (XSS). As such, you should be cautious when working with sensitive
information. It’s advisable to assess security implications and consider other alternatives
where necessary.
3. Not accessible to web workers: Local storage is part of the Window object. As such, it’s
tied to the main execution thread of the web page. This means it's not accessible to web
workers. So if you run any background processes, you cannot use local storage within the
web worker scripts.

Conclusion
Local storage is a feature in modern web browsers that makes it easy for web developers to store
and persist data between browser sessions.

Compared to traditional cookies, it provides larger storage capacities. Also, unlike cookies, it
does not rely on server-side processes. This reduces the need for frequent server requests and
helps improve performance.

In this article, you learn about how to use local storage. We covered saving, retrieving, and
deleting data from local storage. You also learned about some of the benefits of using local
storage in your project, and some of its limitations too.
Map, filter, and reduce are three of the most useful and powerful high-order array methods. In
this tutorial, you'll see how each of these high-order array methods work. You'll also learn where
you'll want to use them and how to use them, with the help of analogies and examples. It’ll be
fun!

How to Use the map() Method


Suppose you have an array arrOne where you’ve stored some numbers, and you’d like to
perform some calculations on each of them. But you also don’t want to mess with the original
array.

This is where map() comes into the picture. The map method will help you do this:

let arrOne = [32, 45, 63, 36, 24, 11]

map() takes a maximum of three arguments, which are value/element, index, and array.

arrOne.map(value/element, index, array)

Let’s say you want to multiply each element by 5 while not changing the original array.

Here's the code to do that:

let arrOne = [32, 45, 63, 36, 24, 11]


const multFive = (num) => {
return num * 5; //'num' here, is the value of the array.
}
let arrTwo = arrOne.map(multFive)
console.log(arrTwo)

And here's the output:

[ 160, 225, 315, 180, 120, 55 ]

So what's going on here? Well, I have an arrOne array with 6 elements in it. Next, I initialized
an arrow function multFive with ‘num’ as an argument. This returns the product of num and 5,
where the ‘num’ variable is fed the data by the map() method.

If you’re new to arrow functions but are familiar with regular functions, an arrow function is the
same as this:

function(num)
{
return num * 5;
}

Then, I initialized another variable arrTwo that will store the new array that the map() method
will create.
On the right-hand side, I called the map() method on the ‘arrOne’ array. So, the map() method
will pick each value of that array starting from the index[0] and perform the desired calculation
on each value. Then it'll form a new array with the calculated values.

Important: Notice how I’m stressing not changing the original array. That is because this
property is what makes the map() method different from the ‘forEach()’ method. The map()
method makes a new array whereas the ‘forEach()’ method mutates/changes the original array
with the calculated array.

How to Use the filter() Method


The name kind of gives it away, doesn't it? You use this method to filter the array based on
conditions you provide. The filter() method also creates a new array.

Let’s take an example: Suppose you have an array arrName and that array stores a bunch of
numbers. Now, you would like to see what numbers can be divided by 3 and make a separate
array from them.

Here's the code to do that:

let arrNum = [15, 39, 20, 32, 30, 45, 22]


function divByFive(num) {
return num % 3 == 0
}
let arrNewNum = arrNum.filter(divByFive)
console.log(arrNewNum)

And here's the output:

[ 15, 39, 30, 45 ]

Let's break down this code. Here, I have an array arrNum with 7 elements in it. Next, I initialized
a function divByFive with ‘num’ as an argument. It returns true or false for each time a new
num is passed for the comparison, where the ‘num’ variable is fed the data by the filter() method.

Then, I initialized another variable arrNewNum that will store the new array that the filter()
method will create.

On the right-hand side, I called the filter() method on the arrNum array. So, the filter() method
will pick each value of that array starting from the index[0] and perform the operation on each
value. Then it'll form a new array with the calculated values.

How to Use the reduce() Method


Let’s say you are asked to find the sum of all elements of an array. Now, you could use a for
loop or the forEach() method, but reduce is built for this kind of task.
The reduce() method reduces an array to a single value by performing the desired operation on
the elements collectively.

Let’s take the above example and use reduce on it:

let arrNum = [15, 39, 20, 32, 30, 45, 22]


function sumOfEle(num, ind) {
return num + ind;
}
let arrNum2 = arrNum.reduce(sumOfEle)
console.log(arrNum2)

Here's the output:

203

Everything is the same as the map() and filter() methods – but what’s important to understand is
how the reduce method works under the hood.

There’s not a definite syntax of the reduce() method. Let’s see the simplest one and that will give
you the gist of all the ways you can use reduce().

Here's some example syntax for reduce():

//Taking the above array for an example


let arrNum = [15, 39, 20, 32, 30, 45, 22]arr.reduce((a1, a2) => {
return a1 + a2
})

Take a look at this syntax. Here, reduce is taking two arguments, a1 and a2, where a1 acts as an
accumulator while the a2 has the index value.

Now, on the first run the accumulator is equal to zero and a2 holds the first element of the array.
What reduce does is that it throws the value in the accumulator that a2 holds and increments it to
the next one. After that, the reduce() method performs the operation on both operands. In this
case it is addition.

So, basically a1 is the accumulator which is currently zero and a2 holds 15. After the first run,
the accumulator has 15 in it and a2 is holding the next value which is 39.

So, 0 + 15 = 15

Now, on second run, reduce throws a2’s value, 39 in the accumulator and then performs the
operation on both operands.

So, 15 + 39 = 54
Now, on the third run, the accumulator has a sum of 15 and 39 which is 54. a2 now holds 20
which the reduce method throws at the accumulator which sums up to 54 + 20 = 74.

This process keeps on going until the end of the array.

What is a Higher Order Function?


A higher order function is a function that takes one or more functions as arguments, or returns a
function as its result.

There are several different types of higher order functions like map and reduce. We will discuss
these later in this tutorial. But before that let's first dive deep into what higher order functions
are.

// Callback function, passed as a parameter in the higher order function


function callbackFunction(){
console.log('I am a callback function');
}

// higher order function


function higherOrderFunction(func){
console.log('I am higher order function')
func()
}

higherOrderFunction(callbackFunction);

In the above code higherOrderFunction() is an HOF because we are passing a callback


function as a parameter to it.

The above example is quite simple isn't it? So let's expand it further and see how you can use
HOFs to write more concise and modular code.

How Higher Order Functions Work

So, suppose I want you to write a function that calculates the area and diameter of a circle. As a
beginner, the first solution that comes to our mind is to write each separate function to calculate
area or diameter.

const radius = [1, 2, 3];


// function to calculate area of the circle
const calculateArea = function (radius) {
const output = [];
for(let i = 0; i< radius.length; i++){
output.push(Math.PI * radius[i] * radius[i]);
}
return output;
}
// function to calculate diameter of the circle
const calculateDiameter = function (radius) {
const output = [];
for(let i = 0; i< radius.length; i++){
output.push(2 * radius[i]);
}
return output;
}
console.log(calculateArea(radius));
console.log(calculateDiameter(radius))

But have you noticed the problem with the above code? Aren't we writing almost the same
function again and again with slightly different logic? Also, the functions we have written aren't
reusable, are they?

So, let's see how we can write the same code using HOFs:

const radius = [1, 2, 3];


// logic to clculate area
const area = function(radius){
return Math.PI * radius * radius;
}
// logic to calculate diameter
const diameter = function(radius){
return 2 * radius;
}
// a reusable function to calculate area, diameter, etc
const calculate = function(radius, logic){
const output = [];
for(let i = 0; i < radius.length; i++){
output.push(logic(radius[i]))
}
return output;
}
console.log(calculate(radius, area));
console.log(calculate(radius, diameter));

Now, as you can see in the above code, we have only written a single function calculate() to
calculate the area and diameter of the circle. We only need to write the logic and pass it to
calculate() and the function will do the job.

The code that we have written using HOFs is concise and modular. Each function is doing its
own job and we are not repeating anything here.

Suppose in the future if we want to write a program to calculate the circumference of the circle.
We can simply write the logic to calculate the circumference and pass it to the calculate()
function.

You might also like