Javascript Unit IV
Javascript Unit IV
EXAMPLE:
<html>
<head>
<title> Jump Menu</title>
</head>
<body>
<select id="slt1" onchange="jumpTo()">
<option>Select color</option>
<option value="Red.html">Red</option>
<option value="Green.html">Green</option>
<option value="Blue.html">blue</option>
</select>
<script>
function jumpTo()
{
var jumpLocation = document.getElementById("slt1").value;
window.location= jumpLocation;
}
</script>
</body>
</html>
This code is creating a jump menu, which is a drop-down menu that allows the user to
select an option and then be taken to a different page or location.
The <select> tag is used to create the drop-down menu, and each <option> tag represents
one of the options in the menu.
The first line of JavaScript code creates a function called "jumpTo", which will be
triggered when there is a change in the selected option in the drop-down menu.
This function will get the value of whatever option was selected using
document.getElementById(), which takes in an element's ID as its parameter and returns
that element.
In this case, it gets the value of "slt1", which is assigned to our <select> tag.
Next, we use window.location to set where we want our browser window to go after an
option has been selected.
We assign this new location by setting it equal to our variable "jumpLocation".
So essentially, when an option is selected from our jump menu, this function will take us
to that specific location.
Overall, this code demonstrates how HTML elements can be manipulated using
JavaScript functions like getElementById() and how we can use these functions along
with event handlers (in this case onchange) to create interactive features on web pages.
The code creates a drop-down menu with different color options and allows the user to
select a color.
When a color is selected, the function "jumpTo()" is called which retrieves the value of
the selected option and redirects the user to the corresponding HTML page for that color.
Dynamic menus in JavaScript offer a versatile and interactive solution for creating
navigation systems on websites.
By combining HTML markup with JavaScript interactivity, developers can build menus
that adapt to user actions, preferences, and data changes, enhancing the overall user
experience and usability of the website.
A dynamic menu in JavaScript refers to a type of menu system on a website that is
interactive and changes dynamically based on user interaction or other factors.
Dynamic menus are used to create interactive navigation systems on websites that adapt
to user actions, preferences, or data changes.
They provide a flexible and customizable way to present options and features to users.
Advantages:
Customization:
Dynamic menus can be highly customizable, allowing developers to tailor the menu's behavior,
appearance, and content to suit specific requirements or user preferences.
Interactivity:
Dynamic menus enhance user interaction by responding to user actions in real-time, providing
feedback, and adapting to changing conditions dynamically.
Efficiency:
By fetching data asynchronously and updating the menu dynamically, dynamic menus can
improve performance and reduce page load times compared to static menu systems.
Example:
<html>
<head></head>
<body>
<select id="slt1" onchange="dynamicMenu()">
<option>Select course</option>
<option value="semI">FYBCA Sem I</option>
<option value="semII">FYBCA Sem II</option>
</select>
<select id="slt2"></select>
<script>
function dynamicMenu()
{
var select1 = document.getElementById("slt1").value;
var select2 = document.getElementById("slt2");
if(select1 === 'semI')
{
var opt1 = document.createElement("option");
opt1.value="C";
opt1.innerHTML ="Programming in C";
select2.options.add(opt1);
}
if(select1 === 'semII')
{
var opt2 = document.createElement("option");
opt2.value="JS";
opt2.innerHTML ="JavaScript";
select2.options.add(opt2);
}
}
</script>
</body>
</html>
The code starts by creating a select element with an id of "slt1" and an onchange event that
calls the function dynamicMenu().
This select element has three options, one default option and two course options for FYBCA
Sem I and II.
Next, there is another select element with an id of "slt2".
This will be used to display the dynamically generated menu based on the user's selection in
the first select element.
Moving on to the JavaScript code, we have a function called dynamicMenu() which is
triggered when there is a change in the value of "slt1".
Inside this function, we get the value of "slt1" using document.getElementById() method
and store it in a variable called 'select1'.
Then we get a reference to our second select element using document.getElementById()
method and store it in 'select2' variable.
We use if statements to check what value was selected in "slt1".
If it is equal to 'semI', then we create an option element using document.createElement()
method.
We set its value as 'C' (short for C programming language) and innerHTML as
'Programming in C'.
Finally, we add this newly created option to our second select element using options.add()
method.
Similarly, if semII was selected from slt1, then another option will be created with value as
JS (short for JavaScript) and innerHTML as JavaScript.
Again this new option will be added to our second select element.
The code creates two drop-down menus, the first one is a static menu with three options and
the second one is a dynamic menu that changes based on the user's selection.
The dynamic menu will display different options depending on what the user selects in the
first menu.
Requiring fields
Requiring fields in JavaScript is an essential aspect of data validation, ensuring that objects or
data structures contain the necessary information before they are used in a program.
It is important for maintaining data integrity, preventing errors, and enhancing the reliability of
our code.
required field is a form input field that must have a non-blank value to be valid. For example,
when creating a plan, the name, ID, bill every, currency, and price fields are mandatory.
Similarly, for user registration username, fullname and password is mandatory Required fields
are usually marked with an orange asterisk. The indicator should be placed right before the form
field so that users can read it to understand the field is mandatory . Using an asterisk to mark
required fields can improve the usability of forms. To validate a required field in JavaScript,
you can use the required attribute on the input element. This will prevent the form from being
submitted if the field is left empty.
Example:
<html>
<body>
<form>
Name: <input type="text" id="myText" name="fname" required>
<input type="submit">
</form>
<p id="demo"></p>
<script>
var x = document.getElementById("myText").required;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
The code is creating a form with an input field for the user to enter their name.
The "required" attribute is added to the input field, which means that the user must fill in
this field before submitting the form.
In order to access this required attribute, the code uses JavaScript's getElementById()
method to select and store the value of the input element with id="myText".
This stored value is then assigned to a variable called x.
Next, using document.getElementById(), another element on the page with id="demo" is
selected and its innerHTML property is set equal to x.
This means that whatever value was stored in x (in this case, whether or not "required" was
present) will be displayed on the webpage within this paragraph element.
Overall, this code demonstrates how JavaScript can be used to manipulate HTML elements
and retrieve information from them.
It also shows how attributes like "required" can be used in forms for validation purposes.
The code is an HTML form that prompts the user to enter their name and when the submit
button is clicked, it will display a message indicating that the input field is required.
Cross-checking fields
It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form validation.
Example:
In this example, we are going to validate the name and password. The name can’t be empty and
password can’t be less than 6 characters long.
<html>
<body>
<script>
function validateform()
{
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name=="")
{
alert("Name can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
The code starts by defining a function called "validateform" which will be used to check if
the user has entered a valid name and password.
Variables will store the values entered by the user in the form fields with names "name" and
"password".
The first if statement checks if the value of variable "name" is equal to null or an empty
string.
If this condition is true, it means that no value was entered for the name field, so an alert
message is displayed saying that name can't be blank.
The else if statement checks if the length of variable "password" is less than 6 characters.
If this condition is true, it means that the password entered by the user is not long enough
(less than 6 characters), so an alert message is displayed saying that password must be at
least 6 characters long.
If both conditions are false, it means that both fields have been filled out correctly and no
alerts will be displayed.
Finally, onsubmit event handler calls validateform() function when submit button in clicked
on.
This ensures that before submitting any data to server-side script for processing, validation
takes place first using JavaScript.
In summary, this code uses basic programming concepts such as functions (to define
reusable blocks of code), variables (to store data) and conditional statements (if/else) to
perform form validation before submitting data to a server-side script for further processing.
The code is a form validation function that checks if the user has entered a name and
password with at least 6 characters before submitting the form.
If either of these conditions is not met, an alert message will be displayed and the form will
not be submitted.
Errors can be coding errors made by the programmer, errors due to wrong input, and other
unforeseeable things.
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.
When an error occurs, JavaScript will normally stop and generate an error message.
The technical term for this is: JavaScript will throw an exception
JavaScript will actually create an Error object with two properties: name and message.
If you use throw together with try and catch, you can control program flow and generate custom
error messages.
Example:
<html>
<body>
<script>
function myFunction()
{
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try
{
if(x.trim() == "")
{
throw "empty";
}
if(isNaN(x))
{
throw "not a number";
x = Number(x);
}
}
catch(err)
{
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
The code starts by creating a function called "myFunction" which will be executed when the
button is clicked.
Inside this function, there is a variable called "message" that stores the HTML element with
the id "p01".
This element will be used to display any error messages.
Next, the value of the input field with id "demo" is stored in a variable called x.
The try block begins and inside it, there are two conditions being checked using if
statements.
The first condition checks if the input value is empty or contains only spaces by using the
trim() method.
If this condition evaluates to true, then an error message saying "empty" will be thrown.
The second condition uses isNaN() function to check if x is not a number.
If this condition evaluates to true, then an error message saying "not a number" will be
thrown.
If both these conditions evaluate to false, then nothing happens and program execution
continues outside of the try block.
However, if either one of these conditions evaluates to true, then control jumps into catch
block where err parameter holds whatever was thrown from within try block as its argument.
In our case it would hold either string 'empty' or 'not a number'.
Inside catch block we use innerHTML property on message object (which refers <p> tag)
and assign it some text based on what was caught in err parameter - whether it's 'empty' or
'not a number'.
Finally after all lines have been executed successfully
The code takes a user input and checks if it is a number or not, displaying an error message
if it is not a number or if the input is empty.
Verifying radio button selections
In the HTML, the radio buttons allow developers to create multiple options for a choice. Users
can select any option, and we can get its value and know which option users have selected from
the multiple options.
We can access the radio element in JavaScript using various methods. After that, we can use
its checked property to check whether the selected radio button is checked. If the value of the
checked property is true, it means the radio button is selected; otherwise, it’s not selected.
Example:
<html>
<body>
<h3>Using the <i>checked property</i> of the radio button to check whether a radio button is
selected.</h3>
<input type = "radio" name = "radio" value = "male" id = "radio1" > Male </input> <br>
<input type = "radio" name = "radio" value = "female" id = "radio2" > Female </input><br>
<input type = "radio" name = "radio" value = "other" id = "radio3" /> Other </input>
<p id = "output"> </p>
<button onclick = "checkRadio()"> Check radio </button>
<script>
let output = document.getElementById("output");
function checkRadio(){
// accessing the radio buttons
let radio1 = document.getElementById('radio1');
let radio2 = document.getElementById('radio2');
let radio3 = document.getElementById('radio3');
// checking if any radio button is selected
if(radio1.checked){
output.innerHTML = "The radio button with value " + radio1.value + " is checked!";
}
if(radio2.checked){
output.innerHTML = "The radio button with value " + radio2.value + " is checked!";
}
if(radio3.checked){
output.innerHTML = "The radio button with value " + radio3.value + " is checked!";
}
}
</script>
</body>
</html>
The code is using the checked property of radio buttons to determine which one is selected.
This property returns a boolean value, true if the button is checked and false if it's not.
First, the code declares a variable called output and assigns it to an HTML element with id
"output".
This will be used to display the result of which radio button is selected.
Next, there is a function called checkRadio() that will be executed when the user clicks on
the "Check radio" button.
Inside this function, three variables are declared: radio1, radio2, and radio3.
These variables represent each of the three radio buttons in our HTML document.
They are assigned by using getElementById() method which takes in as argument the id
attribute of each input tag.
After declaring these variables, we use an if statement to check whether any of them has
been checked or not.
If they have been checked (meaning their checked property returns true), then we use
innerHTML property on our output variable to display a message indicating which one was
selected.
Finally, outside of our function definition but still inside <script> tags, we call our
checkRadio() function when clicking on "Check Radio" button by adding onclick event
handler attribute with its value set equal to "checkRadio()" - meaning execute this function
when clicked.
This way we can easily determine which option was chosen from multiple options without
having to loop through all elements like you would do for checkboxes.
The code attempts to check which radio button is selected and display a message with the
value of the selected radio button.
You might have noticed that sometimes websites like e-commerce or some government
website have two address fields in their forms. One for the primary address and another for
the secondary address(or one for the billing address and another for the shipping address etc).
Most of the time people have the same primary and secondary addresses and to save us from
the tedious work of re-entering the same data again they have some kind of option to
automatically copy the contents of one field into another.
Example:
there is a checkbox and whenever it is checked, the code automatically copies values from the
primary address and primary zip code to the secondary address and secondary zip code
respectively. If the checkbox is unchecked, these fields will go blank.
<html>
<body>
<h1>AutoFill Form</h1>
<form>
<div>
</div>
<div>
</div>
</form>
<script>
function addressFunction()
{
if (document.getElementById( "same").checked)
document.getElementById( "secondaryaddress").value =
document.getElementById( "primaryaddress").value;
else
</script>
</body>
</html>
Example:
<html>
<body>
<form onsubmit=”chkEmailFunc()”>
Enter email id: <input type=”email” id=” txtEmail”>
<input type=”submit”>
</form>
<script>
function chkEmailFunc()
{
The code above is a simple form that asks the user to enter their email address and then
submits it.
The goal of this code is to check if the entered email address is valid or not.
First, we have a function called "chkEmailFunc()" which will be triggered when the form is
submitted.
This function starts by getting the value of the input field with id "txtEmail" using
document.getElementById() method and storing it in a variable called "email".
Next, we have declared a regular expression pattern for validating an email address.
Regular expressions are used to match patterns in strings and can be very useful for tasks
like validation.
In this case, our pattern checks for any combination of letters (both uppercase and
lowercase), numbers, followed by "@" symbol, then another set of letters followed by "."
symbol and finally one more set of letters.
After declaring our pattern, we use .test() method on our pattern object passing in our
"email" variable as an argument.
This method returns either true or false depending on whether there was a match between
our string (email) and the given regular expression (pattern).
We store this result in another variable called "isValid".
Finally, we print out the value of isValid variable to console using console.log().
This will help us see if our validation worked correctly or not.
Some important programming concepts used here include: 1) Functions: A function is a
block of reusable code that performs specific task(s).
In this case, chkEmailFunc() function performs
The code attempts to check the validity of an email address entered by the user and log the
result in the console.
Responding to window events
JavaScript window events are actions that occur when the user does something affecting the
entire browser window, like loading, resizing, closing, or moving the window.
The most common window event is simply loading the window by opening a particular web
page. This event is handled by the onload event handler.
window events happen and hold association with the window object; this global object
represents the web browser's window.
Event Description
Name
load Triggered when the entire web page, including all its
resources, has finished loading.
unload Fired when the user is leaving the page or closing the
browser window or tab.
resize Activated when the size of the browser window is
changed.
scroll Fired when the user scrolls the page.
Example:
<html>
<head>
<title>Window Events Example</title>
<script>
window.addEventListener('load', windowLoad);
function windowLoad ()
{
alert('The page has finished loading!');
}
window.addEventListener('resize', windowResize);
function windowResize()
{
alert("Page has been resized");
}
window.addEventListener('scroll', windowScroll);
function windowScroll()
{
alert('You have scrolled on this page.');
}
</script>
</head>
<body>
</body>
</html>
The code starts by creating a windowLoad function that is triggered when the page finishes
loading.
This function uses the alert() method to display a message saying "The page has finished
loading!".
Next, there is a windowResize function that is triggered whenever the user resizes the
browser window.
This function also uses the alert() method to display a message saying "Page has been
resized".
Lastly, there is a windowScroll function that is triggered when the user scrolls on the page.
Again, this function uses the alert() method to display a message saying "You have scrolled
on this page."
All of these functions are then added as event listeners using the addEventListener()
method.
This allows them to be executed whenever their corresponding events occur (page load,
resize, and scroll).
Overall, this code demonstrates how event listeners can be used in JavaScript to trigger
specific actions based on different events happening in an application or webpage.
The code adds event listeners to alert the user when the window has finished loading, when
the window is resized, and when the user scrolls on the page.
Mouseover
When the mouse cursor passes on the HTML element, the onmouseover event is worked and
shows user-defined functionality. This function also works when the mouse cursor selects the
user element, html tag, or required data. When a user moves the cursor away from an element,
the onmouseover event is activated when the mouseout function not uses. The mouseover
function works with the mouseout function to deactivate the function. For instance, a link can
be highlighted using an onmouseover event anytime after removing the mouse pointer link
shows normal.
Mouseout
When the mouse cursor removes the HTML element, the onmouseout event is worked and
works with user-defined functionality. This function is operated on the user element. html tag
and div information when the mouse cursor goes away using event. The mouseout function
works with the mouseout function to disable the function. For instance, a link can be
highlighted using an onmouseout event and removed links highlighted using a mouseout event
through the mouse pointer link.
mousemove
The mousemove event works when a pointer moves within the web tag or around the element.
It is easy to operate mouse movement just using the point of the mouse. The mousemove event
takes part in an event handler. It is an execution in the script tag to respond to a certain mouse
operation or movement.
Every time the pointer moves on the required part of the page, the mousemove executes and
operates the code. The mousemove is one of the important mouse events like mouseup,
mouseout, click, mousedown, and other work with the MouseEvent interface.
Example:
<html>
<head>
<title> Mouseover function in javascript </title>
<style>
div
{
border: 1px solid black;
background-color: gree;
}
</style>
</head>
<body>
<h2> JavaScript Mouse over Method </h2>
<div id = "demoDIV" onmouseover = " onmouseoverFunction()" onmouseout = "
onmouseoutFunction()" onmousemove = " onmousemoveFunction()" >
The javascript mouse over, mouse out event works to place a pointer or move the pointer
on the particular tag. It is a mouse event to handle functionality with the pointer.
</div>
<script>
function onmouseoverFunction()
{
document.getElementById("demoDIV").style. backgroundcolor = "blue";
}
function onmouseoutFunction()
{
document.getElementById("demoDIV").style. backgroundcolor = "Red";
}
function onmousemoveFunction()
{
document.getElementById("demoDIV").style. backgroundcolor = "yellow";
}
</script>
</body>
</html>
onclick
The onclick event generally occurs when the user clicks on an element. It allows the
programmer to execute a JavaScript's function when an element gets clicked. This event can be
used for validating a form, warning messages and many more.
Example:
<html>
<head>
<script>
function fun()
{
alert("Welcome ");
}
</script>
</head>
<body>
<h3> This is an example of using onclick attribute in HTML. </h3>
<button onclick = "fun()">Click me</button>
</body>
</html>
mousedown
The mousedown event uses the mouse movement on the web page using the javascript
functionality. The mouse-down event works on the laptop's mouse, or single mouse click. If we
press the on a laptop, the mouse down event starts its handling functionality.
Example:
<html>
<head>
<script>
function fun()
{
alert("Welcome ");
}
</script>
</head>
<body>
<h3> This is an example of using onmousedown attribute in HTML. </h3>
<button onmousedown = "fun()">Click me</button>
</body>
</html>
mouseup
The mouseup event works with the mouse movement on the web page using the javascript
functionality. The mouse-up event works on the laptop's mouse, or a single mouse click using
the mouseEvent event. If we release the press button on the laptop, then the mouse-up event
starts its handling functionality.
If the mouse event function (mouseup) uses clicked mouse button after releasing the press
button. It is similar to the mouse down function but has to click completely.
Example:
<html>
<head>
<script>
function fun()
{
alert("Welcome ");
}
</script>
</head>
<body>
<h3> This is an example of using onmouseup attribute in HTML. </h3>
<button on mouseup = "fun()">Click me</button>
</body>
</html>
onblur is an in-built event that is available in JavaScript which gets triggered when the elements
on which it is applied loses its focus.
This is one of the significant events from the events which are supported by JavaScript.
This event is fired when the item comes out of focus on the web page.
onblur event is mostly used with the input field element such as in form where input validation
can be performed for example when the user enters input into the field and goes to the next
element, the onblur event can be attached on that field and validation can be performed.
Example:
<html>
<body>
<input type = "text" id = "myText" onblur = "fireEvent()" >
<script >
function fireEvent( )
{
document.getElementById( "myText" ).style.backgroundColor = 'blue';
}
</script>
</body>
</html>
The code above is a simple HTML document that contains an input field with the id
"myText".
This input field has an event listener attached to it, the "onblur" event.
This means that when the user clicks outside of the input field (i.e. loses focus), the function
"fireEvent()" will be triggered.
The function itself uses JavaScript to access the element with id "myText" and change its
style property, its background color, to blue.
This means that when the user clicks outside of the input field, it will turn blue.
Event listeners: These are functions or pieces of code that are executed in response to
certain events happening on a webpage.
onblur event listener triggers our function when a specific action (clicking outside of an
input field) occurs.
The Document Object Model (DOM) is a representation of all elements on a webpage as
objects.
By using JavaScript to access and modify these objects, we can dynamically change how
they appear or behave on our page.
In this case, we use document.getElementById() to select our input field and then change its
style property.
A function is a block of reusable code that performs a specific task.
In this example, our fireEvent() function changes the background color of our input field but
could potentially do any number of other tasks depending on what we want it to do.
The code changes the background color of the text box to blue when the user clicks out of
the text box.
Responding to onFocus form events
In JavaScript, onfocus is an attribute that works when the focus is on any element.
This attribute is commonly used with elements such as <input>, <a>, <select>. This event
attribute is sustained by every HTML element except the ones like <base>, <head>, <bdo>,
<br>, <html>, <meta>, <iframe>, <param>, <style>, <script>, and <title> elements.
This event handler executes when an element becomes focus on the user’s screen. The elements
focus can be when the user clicks on a text box. At that time, it is in focus by the user since the
person has clicked on it.
Example:
<html>
<body>
User Name: <input type="text" id="fname" onfocus="func(this.id)"><br>
Confirm user name: <input type="text" id="lname" onfocus="func(this.id)">
<script>
function func(x) {
document.getElementById(x).style.background = "red";
}
</script>
</body>
</html>
The code is creating a simple form with two input fields for the user's name and
confirmation of their name.
The first field has an id of "fname" and the second field has an id of "lname".
In order to add some interactivity, the onfocus event handler is added to both input fields.
This means that when the user clicks or tabs into either field, the function named "func" will
be triggered.
The func() function takes in one parameter (x) which represents the id of whichever input
field was clicked on.
Inside this function, we use document.getElementById() to access that specific element
using its id.
Then we use .style.background to change its background color property to red.
This demonstrates how JavaScript can manipulate HTML elements by accessing them
through their ids and changing their properties dynamically based on events like clicking or
tabbing into a form field.
Overall, this code shows how event handlers can be used in JavaScript to make web pages
more interactive and responsive for users.
The code will create a simple HTML page with two input fields for user name and
confirmation, and when the user clicks on either field, it will trigger a JavaScript function
that changes the background color of the field to red.
keydown event
When the key is pressed and still key in the down place of the keyboard, then the Javascript key
down event work on the application. The keyboard event works for input values of the web
page, like forms, search bar, and other elements.
Example
The alert tab shows the user-defined functionality after the key-down function works.
<html>
<body>
<script>
function keyDownFunction()
</script>
</body>
</html>
This HTML code creates a simple webpage with an input field. When a key is pressed
down in the input field, the `keyDownFunction` JavaScript function is triggered.
The `<input>` tag creates an input field of type text with the id "input_class" and a
placeholder text "write here."
The `onkeydown` attribute is set to call the `keyDownFunction` function when a key is
pressed down in the input field.
The `<script>` tag contains the `keyDownFunction` JavaScript function, which displays
an alert with the message "JavaScript keyDown function activates successfully!!!" when
called.
When the user interacts with the input field by pressing a key, the alert message will be
displayed on the webpage.
The DOM, Nodes, and Objects
DOM
When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.
The Document Object Model (DOM) is a programming interface for HTML and XML
documents. It defines the logical structure of documents and the way a document is accessed
and manipulated.
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.
Advantages of DOM:
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.
Properties of 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.
Nodes
In JavaScript, a DOM Node refers to an object that represents a node in the Document Object
Model (DOM), which is a programming interface for HTML and XML documents. There are
different types of nodes, including element nodes, text nodes, and comment nodes.
Node Types
ELEMENT_NODE
ATTRIBUTE_NODE
ENTITY_NODE
ENTITY_REFERENCE_NODE
DOCUMENT_FRAGMENT_NODE
TEXT_NODE
CDATA_SECTION_NODE
COMMENT_NODE
PROCESSING_INSTRUCTION_NODE
DOCUMENT_NODE
DOCUMENT_TYPE_NODE
NOTATION_NODE
Methods
appendChild(Node newChild)
This method adds a node after the last child node of the specified element node. It
returns the added node.
cloneNode(boolean deep)
This method is used to create a duplicate node, when overridden in a derived class. It
returns the duplicated node.
hasAttributes()
Returns whether this node (if it is an element) has any attributes or not. Returns true if
any attribute is present in the specified node else returns false. This has been removed.
Refer specs.
hasChildNodes()
Returns whether this node has any children. This method returns true if the current node
has child nodes otherwise false.
insertBefore(Node newChild, Node refChild)
This method is used to insert a new node as a child of this node, directly before an
existing child of this node. It returns the node being inserted.
removeChild(Node oldChild)
This method is used to remove a specified child node from the current node. This
returns the node removed.
Objects
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.
The window object is the topmost object of DOM hierarchy. It represents a browser window
or frame that displays the contents of the webpage. Whenever a window appears on the screen
to display the contents of document, the window object is created. The properties and methods
of Window object that are commonly used are listed in the below table:
Properties of the Window Object
Property Purpose
Name
Closed It holds a Boolean value that represents whether the window is closed or not.
console It returns a reference to the console object which provides access to the
browser’s debugging console.
Document It returns a reference to the document object of that window.
History It provides information of the URLs visited in the current window.
Length It represents the number of frames in the current window.
fullScreen This property indicates whether the window is displayed in full screen or not.
Location It contains the URL of the current window.
Opener It contains a reference to the window that opened the current window.
Screen It refers to the screen object
Window It returns the current window or frame.
Navigator It returns a reference to the navigator object.
outerHeight It will get height of the outside of the browser window.
outerWidth It will get width of the outside of the browser window.
Toolbar It will result the toolbar object, whose visibility can be toggled in the window.
To access the properties of the window object, you will specify object name followed by a
period symbol (.) and the property name.
The JavaScript date object can be used to get year, month and day. You can display a timer on
the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to get and set
day, month, year, hour, minute and seconds.
Constructor
You can use 4 variant of Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
JavaScript Date Methods Methods Description
getDate() It returns the integer value between 1
and 31 that represents the day for the
specified date on the basis of local
time.
getDay() It returns the integer value between 0
and 6 that represents the day of the
week on the basis of local time.
getFullYears() It returns the integer value that
represents the year on
getHours() It returns the integer value between 0
and 23 that