Java Script DOM
Introduction to Java Script
What is JavaScript DOM
Element Access in Java Scripts
Document Object
Window Object
Events in Java Scripts
What is JavaScript DOM
DOM stands for Document Object Model. But what does
that mean? Let's break it down.
The Document part refers to the webpage you see in the
browser. Specifically, the HTML Document which handles
the structure of the page's content. This includes the text,
images, links, and other elements that make up the page.
Object means the elements like images, headers, and
paragraphs are treated like objects. Each object has its
properties (like id, class, style) and methods. Using these
properties and methods, you can manipulate the
elements.
The Model in DOM means it's a representation or copy of
the HTML document as a hierarchical tree. This tree
includes all the elements. And it captures the parent-child
relationships between them.
It is represented as a tree hierarchy structure
What You Can Do With the DOM
DOM manipulation allows developers to interact with the structure, style,
and content of web pages. The following are some of the things you can
do with the DOM:
1. Change and remove existing elements in the DOM.
2. Create and add new elements to the page.
3. Change the styles for elements.
4. Add event listeners to the elements to make them interactive.
Simple Example
<html>
<head>
<title> Tree </title>
</head>
<body>
<h1> DOM Testing</h1>
<p title="Paral"> Pragraph text</p>
<table>
<tr>
<td>cell1 </td>
<td>cell2 </td>
</tr>
<tr>
<td>cell1 </td>
<td>cell2 </td>
</tr>
Element Access in Java Scripts
In JavaScript, HTML elements are accessed and manipulated through the
Document Object Model (DOM). The document object represents the
entire HTML document and provides methods to find and interact with its
elements. To facilitate this, we can move ahead and change the HTML
element by using the following techniques −
1. Get HTML element by Id
2. Get HTML element by className
3. Get HTML element by Name
4. Get HTML element by tagName
5. Get HTML element by CSS Selector
Get HTML element by Id
This method gets the element from a unique ID and lets the user access
that element. Users can use the getElementById() method to access and
update the HTML content. If any element does not exist with the given
Id, the method returns null.
Syntax
document.getElementById(element_ID);
Parameter − It takes the element id for the element to be accessed.
Return value − It returns the object with the particular id. If the element
with the particular id doesn’t exist, null is returned.
Example 1
#Filename: index.html
<html>
<head>
<title>DOM getElementById() Method</title>
</head>
<body>
<h1 id="elementId" style="color: green;">
Welcome To DOM Tutorials
</h1>
<p>DOM getElementById() Method</p>
<script>
// Accessing the element by getElementById method
var temp = document.getElementById("elementId");
console.log(temp);
console.log(temp.innerHTML);
</script>
<body>
</html>
Get HTML element by className
This selects the element from the class name. We can provide a class
name to each element in HTML and then access the same using that class
name. In this we are going to use the method getElementsByClassName()
to get and update the element.
Syntax
document.getElementsByClassName(classnames);
Parameter − It takes input for class names of the element that needs to
be accessed.
Return value − It returns the collection of objects that have a particular
class name. Users can access this collection using the indexes.
<html>
<head>
<title>DOM getElementsByClassName() Method</title>
</head>
<body>
<h1 style="color: green;">Welcome To Tutorials Point</h1>
<!-- Multiple html element with GeeksforGeeks class name -->
<p class="className">One #1</p>
<p class="className">Two #2</p>
<p class="className">Three #3</p>
<b>DOM getElementsByclassName() Method</b>
<script>
// Accessing the element by getElementsByclassName method
var temp = document.getElementsByClassName("className");
console.log(temp[0]);
console.log(temp[1]);
console.log(temp[2]);
</script>
</body>
</html>
Window Object
The window object in JavaScript represents the browser window or a
frame containing a webpage. It is the global object in a browser
environment, meaning that all global variables, functions, and objects are
properties or methods of the window object.
Key aspects of the window object:
Global Scope:
In the browser, the window object serves as the global scope. This means that variables
declared without const, let, or var become properties of the window object, and global
functions become its methods.
Browser Interaction:
It provides properties and methods for interacting with the browser window itself, such
as:
Opening/Closing Windows: window.open(), window.close().
Resizing/Moving Windows: window.resizeTo(), window.moveTo().
Scrolling: window.scrollTo()
Accessing Browser Features:
It offers access to various browser features and objects:
window.document: Represents the HTML document loaded in the window, allowing
manipulation of the Document Object Model (DOM).
window.location: Provides information about the current URL and allows for navigation.
window.history: Allows interaction with the browser's session history.
window.navigator: Contains information about the browser and operating system.
window.screen: Provides information about the user's screen dimensions.
Dialog Boxes:
It includes methods for displaying various types of dialog boxes:
window.alert(): Displays a simple alert message.
window.confirm(): Displays a message with "OK" and "Cancel" options.
window.prompt(): Displays a message and prompts the user for text input.
Example
In the below code, we have defined the 'num' global and local variables
inside the function. Also, we have defined the 'car' global object.
In the test() function, we access thefunction
globaltest()
num { variable's value using the
let num = 300;
'window' object.
<html> document.getElementById("output1").innerHTML
<body> += window.num;
<div id = "output1">The value of the global num
variable is: </div> document.getElementById("output2").innerHTML
<div id = "output2">The value of the local num+= num;
variable is: </div>
<div id = "output3">The value of the car object
document.getElementById("output3").innerHTML
is: </div> += car.brand;
<script> }
var num = 100; test();
const car = { </script>
brand: "Honda", Output</body>
model: "city", The value of the global num variable is:
</html>
} 100
The value of the local num variable is:
300
Property Name Property Description
closed When the particular window is closed, it returns true.
console It returns the window's console object.
customElements It is used to define and access the custom elements in the browser window.
devicePixelRatio It returns the physical pixel ratio of the device divided by CSS pixel ratio.
document It is used to access the HTML document opened in the current window.
It is used to get the window items like iframes, which are opened in the current
frames
window.
frameElement It returns the current frame of the window.
history It is used to get the history object of the window.
It returns the inner height of the window without including the scroll bar, toolbar,
innerHeight
etc.
It returns the inner width of the window without including the scroll bar, toolbar,
innerWidth
etc.
length It returns the total number of iframes in the current window.
localStorage It is used to access the local storage of the current window.
location It is used to access the location object of the current window.
name It is used to get or set the name of the window.
navigator It is used to get the Navigator object of the browser.
opener It returns a reference to the window from where the current window is opened.
outerHeight It returns the total height of the window.
outerWidth It returns the total width of the window.
pageXOffset It returns the number of pixels you have scrolled the web page horizontally.
pageYOffset It returns the number of pixels you have scrolled the web page vertically.
parent It contains the reference to the parent window of the current window.
scheduler It is entry point for using the prioritized task scheduling.
screen It returns the 'screen' object of the current window.
It returns the position of the x-coordinate of the current window relative to the
screenLeft
screen in pixels.
It returns the position of the y-coordinate of the current window relative to the
screenTop
screen in pixels.
screenX It is similar to the screenLeft property.
screenY It is similar to the screenTop property.
scrollX It is similar to the pageXOffset.
scrollY It is similar to the pageYOffset.
self It is used to get the current state of the window.
sessionStorage It lets you access the 'sessionStorage' object of the current window.
speechSynthesis It allows you to use the web speech API.
visualViewPort It returns the object containing the viewport of the current window.
top It contains a reference to the topmost window.
Here, we will cover some properties with examples.
OuterHeight/OuterWidth Properties of the Window object
The outerHeight property of the window object returns the window's height, and the
outerWidth property of the window object returns the window's width.
Example
In the code below, we used the outerHeight and outerWidth property to
get the dimensions of the window. You can change the size of the window
and observe changes in the value of these properties.
<html>
<body>
<p id = "output1">The outer width of the window is:
</p>
<p id = "output2">The outer height of the window is:
</p>
<script>
const outerHeight = window.outerHeight;
Output
const outerWidth = window.outerWidth; The outer width of the window is:
document.getElementById("output1").innerHTML +=
outerWidth;
1536
document.getElementById("output2").innerHTML += The outer height of the window
outerHeight;
</script>
is: 816
</body>
ScreenLeft Property of the Window Object
The window screenLeft property returns the left position of the current window.
Example
In the output of the below code, you can see the left position of the current window in
pixels.
<html>
<body>
<div id = "output">Your browser window is left by: </div>
<script>
const screenLeft = window.screenLeft;
document.getElementById("output").innerHTML += screenLeft + " px.";
</script>
</body>
</html>
Output
Your browser window is left by: 0 px.
Window Object Methods
The 'window' object also contains methods like properties to manipulate
the current browser window.
In the below table, we have covered the methods of the 'window' object
with their description. You may use 'window' as a reference to access and
invoke the below methods to make the code readable.
Method Name Method Description
alert() It is used to show the alert message to the visitors.
atob() It converts the string into the base-64 string.
blur() It removes the focus from the window.
btoa() It decodes the base-64 string in the normal string.
JavaScript window.alert() Method
The window.alert() method allows you to show the pop-up dialog
containing the message, warning, etc. It takes the string text as an
argument.
Example
In the below example, when you click the button, it will invoke the
alert_func() function and show the pop-up box at the middle top.
<html>
<body>
<button onclick = "alert_func()"> Execute Alert
</button>
<script>
function alert_func() {
window.alert("The alert_func funciton is
executed!");
}
</script>
</body>
</html>
JavaScript window.open() Method
The window.open() method is used to open a new window. It takes a URL as an
argument, which you need to open in a new window.
In the below code, we used the window.open() method to open a new window in the
browser. You can see that the code opens the home page of the 'tutorialspoint' website
in the new window.
<html>
<body>
<button onclick = "openWindow()"> Open New Window </button>
<script>
function openWindow() {
window.open("https://www.google.com/");
}
</script>
</body>
</html>
JavaScript window.print() Method
The window.print() method lets you print the web page.
Example
In the below code, click the button to print the web page.
<html>
<body>
<h2> Hello World! </h2>
<button onclick = "printPage()"> Print Webpage </button>
<script>
function printPage() {
window.print();
}
</script>
</body>
</html>