0% found this document useful (0 votes)
2 views25 pages

DOM

The document explains the Browser Object Model (BOM) and Document Object Model (DOM) in JavaScript, detailing how they enable interaction with the browser and web documents. It covers key components such as window, location, navigator, and methods for manipulating HTML elements and handling events. Additionally, it discusses JSON for data transport, time delays with setTimeout and setInterval, and the use of promises and async/await for managing asynchronous operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views25 pages

DOM

The document explains the Browser Object Model (BOM) and Document Object Model (DOM) in JavaScript, detailing how they enable interaction with the browser and web documents. It covers key components such as window, location, navigator, and methods for manipulating HTML elements and handling events. Additionally, it discusses JSON for data transport, time delays with setTimeout and setInterval, and the use of promises and async/await for managing asynchronous operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

BOM and DOM

BROWSER OBJECT MODEL AND DOCUMENT OBJECT MODEL


BOM(Browser Object Model)

 The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
 "BOM" stands for Browser Object Model. It represents the objects that a browser
provides to JavaScript to interact with the browser itself.
 The BOM includes objects like:
BOM
Window: The global object in a browser's environment. It represents the browser window or
tab and contains properties like window. location (which gives information about the
current URL), window. document (which refers to the DOM document in the current
window), and many others.

1. Document: Represents the DOM (Document Object Model) of a web page. It provides
methods and properties to interact with the contents of the page.
2. Location: Represents the current URL of the browser and allows you to interact with it.
3. Navigator: Provides information about the browser itself, such as its name, version, and
capabilities.
4. Screen: Represents the user's screen. It provides information about the dimensions and
pixel depth of the screen.
5. History: Allows manipulation of the browser's history (back, forward, etc.).
Window. Screen
 The window.screen object contains information about the user's
screen.
 The window.screen object can be written without the window
prefix

Properties:
•screen.width
•screen.height
•screen.availWidth
•screen.availHeight
•screen.colorDepth
•screen.pixelDepth
Window.location

 The window.location object can be used to get the current page address (URL)
and to redirect the browser to a new page.
 Some examples:
•window.location.href returns the href (URL) of the current page
•window.location.hostname returns the domain name of the web host
•window.location.pathname returns the path and filename of the current page
•window.location.protocol returns the web protocol used (http: or https:)
•window.location.assign() loads a new document
Window.history and window.navigator
 Window.history object contains the browser history.
 Some methods:
•history.back() - same as clicking back in the browser
•history.forward() - same as clicking forward in the browser

➢ Window.navigator object contains information about the visitor’s browser


➢ Examples:
•navigator.cookieEnabled : property returns true if cookies are enabled, otherwise
false.
•navigator.appCodeName :property returns the application code name of the browser.
•navigator.platform : property returns the browser platform (operating system).
JavaScript Popup Boxes

 JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
 An alert box is often used if you want to make sure information comes through to
the user.
 When an alert box pops up, the user will have to click "OK" to proceed.
JavaScript Popup Boxes
Confirm Box
 A confirm box is often used if you want the user to verify or accept
something.
 When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
 If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
JavaScript Popup Boxes
Prompt Box :
 A prompt box is often used if you want the user to input a value
before entering a page.
 When a prompt box pops up, the user will have to click either "OK"
or "Cancel" to proceed after entering an input value.
 If the user clicks "OK" the box returns the input value. If the user
clicks "Cancel" the box returns null.
DOM(Document Object Model)
 In JavaScript, the DOM (Document Object Model) is a programming
interface for web documents. It represents the structure of a document as a
tree-like model where each node is an object representing a part of the
document, such as elements, attributes, and text.
 When a web page is loaded, the browser creates
a Document Object Model of the page.
 The HTML DOM model is constructed as a tree of Objects:
DOM Manipulation

• JavaScript can change all the HTML elements in the page


• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
DOM Methods
 Methods used to target HTML elements in JavaScript file

 getElementById(id): This method allows you to retrieve an element from the


document by its unique id.
 getElementsByClassName(className): This method returns a collection of all
elements in the document with a specified class name.
 getElementsByTagName(tagName): Returns a collection of elements with the
specified tag name.
 querySelector(selector): Returns the first element that matches a specified CSS
selector.
 querySelectorAll(selector): Returns a NodeList of all elements that match a
specified CSS selector.
Changing HTML Elements
Property Description

element.innerHTML = new html content Change the inner HTML of an element

element.attribute = new value Change the attribute value of an HTML


element

element.style.property = new style Change the style of an HTML element

element.setAttribute(attribute, value) Change the attribute value of an HTML


element
Adding and Deleting Elements
Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(new, old) Replace an HTML element

document.write(text) Write into the HTML output stream


DOM Event Listener
 The addEventListener() method attaches an event handler to
the specified element
 The first parameter is the type of the event (like "click" or "mousedown"
or any other HTML DOM Event.)
 The second parameter is the function we want to call when
the event occurs.
 Ex:
element.addEventListener("click", function(){
alert("Hello World!");
});
DOM Events
 Event: An action performed by the user on the webpage is
known as an event
 A JavaScript can be executed when an event occurs, like when a
user clicks on an HTML element.
 Click
 Mouseover
 Contaxmenu
 Doubleclick
 Keypress
 Keydown
 submit
Event Propagation
 Event propagation refers to the way events travel through the DOM tree. When
an event occurs on an element, it can trigger event handlers not only on that
element but also on its parent elements, all the way up to the root of the
document. There are two phases of event propagation:
1. Capturing Phase: The event travels from the root of the DOM tree down to the
target element.
2. Bubbling Phase: The event then bubbles up from the target element back to the
root.
 event.stopPropagation(): This method prevents further propagation of the
current event. It stops the event from bubbling up the DOM tree or from
capturing down the tree
JSON(Java Script Object Notation
 It is format of storing and transporting data.
 It is used when the data is sent form the server to web
page
 It is a popular data format for developers because of its
human readable text, light weight which requires less
coding and faster process
Example: [
{“fname”:”Ram”,”lname”:”Patil”},
{“fname”:”Raj”,”lname”:”smith”},
{“fname”:”Ashish”,”lname”:”gouda”}
]
Syntax of JSON

 Data is in Key value pairs


 Data is separated by ‘,’
 Curly braces holds objects
 [ ]---holds array
In JavaScript, there are two main methods used to work with JSON
(JavaScript Object Notation):
1.JSON.Stringify() : used to convert normal object to JSON format
2.JSON.parse(): Used to convert JSON format of data to normal object
Time delays
 setTimeOut() and setInterval() are two functions in js
allows to schedule tasks to be executed at later time.
Used for animations, polling data from server and other
asynchronous tasks.
 setTimeOut() :
 Runs the code with time delay
Syntax : window.setTimeOut( function , delay ) ;
•function: The function you want to execute.
•delay: The amount of time (in milliseconds) before the function is
executed
Time delays
 setInterval() :
 The function similar to setTimeOut, but it schedules a
function to be executed repeatedly at specified interval.
Syntax : window.setInterval( function , delay ) ;
•function: The function you want to execute.
•delay: The amount of time (in milliseconds) before the function is
executed
 createTimeOut() and createInterval()
 cancel a setTimeout, you use clearTimeout

 cancel a setTimeout, you use clearTimeout


Promises
Promises in JavaScript are a powerful way to work with asynchronous code. They
provide a clean and more readable syntax for handling operations that may take
an unknown amount of time to complete, such as fetching data from a server or
reading a file.
A promise represents the eventual result of an asynchronous operation. It can be
in one of three states:
• Pending: Initial state, neither fulfilled nor rejected.
• Fulfilled: Meaning the operation completed successfully.
• Rejected: Meaning the operation failed.
Syntax to create promise
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation, e.g., fetching data from a server.

if (/* operation successful */) {


resolve('Success data'); // Resolve if successful.
} else {
reject('Error message'); // Reject if there's an error.
}
});
Consuming a Promise:

 Then() : It will executed when the promise will in resolved


state
 Catch() : It will get executed when the promise is in
rejected state
 Finally() : It will execute always means promise is in
resolve , reject or in pending state
Async and await

 "async and await make promises easier to write"


 async makes a function return a Promise
 await makes a function wait for a Promise

 Async : The async keyword is used to define a function that returns a promise. It
allows you to write
 Await : The await keyword is used inside an async function to wait for a Promise
to settle (either resolve or reject). It can only be used inside an async function

You might also like