SlideShare a Scribd company logo
1 of 42
JAVASCRIPT
Document Object Model (DOM)
Browser Object Model (BOM)
Document Object Model
(DOM)
Paraphrased from Wikipedia:
That which we see as a window displaying a document, the browser program sees
as a hierarchical collection of objects. When the browser parses a document, it
creates a collection of objects that define the document and detail how it should be
displayed. The object the browser creates is known as the document object.
The top level of the hierarchy is the window object, which contains the information
not only about the document object, but also about the window displaying the
document.
The DOM applies not only to web browsers, but also to other types of documents
you may have heard of such as XML and XHTML.
When applied to web browsers, the DOM is sometimes referred to as the browser
object model, or BOM.
DOM vs BOM
Browser Object Model (BOM) – A term sometimes applied to the
DOM specifically referring to the browser context. ‘BOM’ is not an
“official” standard. In addition, the BOM is notorious for being
interpreted differently by different browsers. This has always been
a major problem in web development, and is one area rife with
cross-browser compatibility issues.
However, because we will be discussing the DOM only within
the context of using a web browser, you may encounter the use
of BOM as well as DOM.
DOM
The DOM (or BOM) is a set of several common web objects
inherited from the browser "context" that are accessible to
JavaScript
We have already seen a couple of these objects:
window
document
DOM Hierarchy
For the time being, you can think of the above objects as special types of variables.
These special variables are more accurately called 'objects'.
Think of these as variables that have been pre-declared for you. In most cases,
these variables already have values.
As with variables, we can view and / or modify their values.
Inside a ‘window’ object
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<div id="main_content">
<p>A paragraph of content with <i>some text in
italics.</i></p>
<p>A second paragraph of content. This paragraph
also has an image of a <img src="baseball.jpg">
baseball embedded.</p>
</div>
</body>
</html>
Every box in this illustration is called a ‘node’.
In jQuery we would select all paragraphs on the page with: $('p')
In plain JavaScript we would use: window.document.p
window Object
By 'window' we are referring to the part of the browser that surrounds the
HTML document
You can use this window object to open new windows (or tabs), close
existing windows (or tabs), resize windows, change the status of windows,
dealing with frames, working with timers, etc
This object is also your handle to access the lower level items in the
hierarchy (see previous slide).
The window object incudes methods such as alert() and write() (via the
'document' object) that you have seen previously.
The window object is implicit:
In theory, we should need to write: window.alert() or
window.document.write()
However, because it is a global object (beyond the scope of this
discussion), the ‘window’ reference is implicitly understood and,
therefore, typing out window turns out to be optional.
Example: Accessing your images via the DOM
window.document.images
In jQuery: $('img')
Accessing Elements by 'id'
<img src=“firetruck.jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”>
<img src=“baseball.jpg” id=“ball_pic” name=“baseball” alt=“pic of baseball”>
An element can be accessed by its 'id' attribute (if it has one):
alert( document.getElementById('firetruck').alt ); //Outputs: ‘pic of truck’
Accessing Elements by 'name'
<img src=“firetruck.jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”>
<img src=“baseball.jpg” id=“ball_pic” name=“baseball” alt=“pic of baseball”>
An element can be accessed by its 'name' attribute (if it has one):
alert( document.images.firetruck.alt ); //Outputs: ‘pic of truck’
Note that in this case we retrieve all images, and then use the name attribute to
indicate which particular image we want to access.
Accessing Elements by array
<img src=“firetruck.jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”>
<img src=“baseball.jpg” id=“ball_pic” name=“baseball” alt=“pic of baseball”>
You can access an element using array notation:
alert( document.images[0].alt ); //Outputs 'pic of truck'
alert( document.images[1].alt ); //Outputs 'pic of ball'
That is, document.images selects all images in the document. This is analogous to
jQuery's: $('img')
Array notation is simply a way to refer to the items in the numerical order in which
they appear. Note that array notation begins at 0.
Who cares?
Are you impressed yet? Okay, I agree that having all of these different
ways of accessing things may not seem useful. In addition, the fact that
jQuery seems to make it all so much easier.
Patience, grasshopper: Over time in your web-development lives, you will
see that there are situations where the DOM is preferable – even necessary.
In addition, there will be times when you will find that the particular
techniques of accessing elements each have their strengths.
dom_example.htm
<html>
<head>
<title>DOM Example</title>
<script type="text/javascript">
function domTest(){
var images = document.images; //Recall that 'window' is implicit
var str="List of Alt Values:n";
for (var i=0; i<images.length; i++) { //this is called a 'loop'
str += images[i].alt + "n";
}
alert(str);
} //end domTest()
</script>
</head>
<body onload="domTest()">
<p>Some smiley-face balls:</p>
<img src="blue_ball.jpg" alt="Pic of blue ball" height="80" width="80">
<img src="green_ball.jpg" alt="Pic of green ball" height="80" width="80">
<img src="red_ball.jpg" alt="Pic of red ball" height="80" width="80">
</body>
</html>
Examples using pop-up windows
window.alert()
alert(“This is a message”);
window.confirm()
 Returns a boolean:
 True – if user clicks ‘OK’
 False – if user clicks ‘Cancel’
 Example: var result = confirm(“Continue ?”);
window.prompt()
Returns the String entered by the user, if the user clicks ‘OK’
Returns ‘null’ if the user clicks ‘Cancel’
var response = prompt(“Your Name ?”, [default] );
Don't forget that even though these methods are part of the 'window' object,
the reference to 'window' is "implicit" (i.e. it's presence is assumed).
Therefore for clarity, we typically just leave it out.
Opening a new browser window
To open a window (or tab) use:
window.open(arg1, arg2, arg3);
All 3 arguments are optional, All 3 take Strings as their data
types
arg1 - the URL of the document
arg2 - window name (for purposes of referencing if needed)
– Note: This is not the <title> of the window
arg3 - window options to control the appearance of the
window. This is where you indicate all desired options (in one
single string, separated by commas).
Not all options are always available. The options available to you depend on the
context.
Example: window.open("http://google.com", "", "height=600,
width=400, toolbar=no");
window.open("http://google.com", "googWin", "height=600,
width=400, toolbar=no");
window.open("http://google.com", "googWin", "height=600,
width=400, toolbar=yes");
window.open() - options
window.open() - options
Opening a new browser window
var newWindow = window.open("", "winInfo",
"height=200, width=400");
newWindow.document.write('The current date is: ' +
Date() + '<br>');
newWindow.document.write('<input type="button"
value="Greet Me" onclick="alert('hi')">');
• Note how this time, we need to include the reference to the current
window object, 'newWindow' in order to ensure that our code applies
to the appropriate window
• Note the advantage of keeping single and double quotes separate
• Note the need to use escape characters in the 'onclick' attribute
JavaScript API
This is a good time to ask ourselves where to find the
JavaScript API. There are several resources on the
web that provide this information.
One we will check out here is provided by the folks at
Mozilla:
https://developer.mozilla.org/en-US/docs/Web/JavaScript
window.open() API from W3 Schools
http://www.w3schools.com/jsref/met_win_open.asp
Note the need for a 'Browser Support' section.
DOM Hierarchy
frames Object
The frames object has the following properties:
parent
length
name
The parent (frameset) can access the children frames by
their names. The children can access the other child by
going through the parent.
Frames are no longer popular – in fact, their use has fallen
out of favor and rarely recommended.
They are discussed here simply for completeness and
because it is possible you will encounter them in legacy
code.
DOM Hierarchy
location Object
alert( window.location.href ); //outputs the current URL
Recall: alert( location.href ) would also work…
location Object
A URL such as:
http://learning.javascript.info/ch09-01.htm?a=1
Can be broken down into the following property values of the
'location' object:
host/hostname: learningjavascript.info
protocol: http:
search: ?a=1
href: http://learning.javascript.info/ch09-01.htm?a=1
e.g. alert( window.location.protocol ); //outputs ‘http:’
Timing Events
It is possible to time events using JavaScript. There are two functions in
particular that can be useful: setTimeout() and setInterval().
setInterval() will execute a function that you name over and over again at
specified intervals (e.g. every 3 seconds). Of course, you will then need a way
to stop the execution. This is not difficult, but requires some extra code that we
will not get into just now.
setTimeout() will execute a function once, after a certain time interval has
passed.
Both of these methods are part of the ‘window’ object, in exactly the same way
that alert() is a method of the window object.
//Example: set_timeout_example.htm
<html>
<head>
<title>setTimeout() Example</title>
<script type="text/javascript">
function go() {
alert('Ready? Click the okay button, then wait 2 seconds to be greeted.');
//After the user closes the alert box above, we wait 2 seconds
//and then the greetUser() function is invoked
setTimeout("greetUser()",2000);
}
function greetUser() {
alert('Hello!!!');
}
</script>
</head>
<body onload="go()">
</body>
</html>
DOM Hierarchy
navigator Object
Allows you to find out information about the client (e.g. web browser or other
agent) that is accessing your page. Items you can check for / about include:
• The type of browser and related information ('userAgent')
• The version number ('appVersion')
• Whether cookies are enabled ('cookieEnabled')
• The OS on which the client is running ('platform')
• Which plug-ins are installed ('plugins')
• This is a common technique by which your smartphone is redirected to a
'small-screen friendly' version of a web page
'navigator' object properties
Property Description
appCodename name of the browser code base
appName name of the browser code base
appMinorVersion browser minor version
appVersion browser major version
platform platform that browser is on
plugins array of plugins supported
userAgent full agent description for browser
userLanguage language supported by browser
Example: history_navigator_properties.htm
history_navigator_properties.htm
as run on a Windows desktop computer
history_navigator_properties.htm
as run on an iPhone
DOM Hierarchy
document Object
We have now gone through several of the properties of the
window object, albeit somewhat briefly. We will now return to
one object with which we are already somewhat familiar, the
document object.
Of all the objects encapsulated by the window object, the
document object is one JS programmers interact with frequently.
The document object provides access to any element on the
page, either individually or as a collection (e.g. a specific image,
or an array of all of the images).
We've already seen a few properties/methods: getElementById,
getElementByTagName and writeln. Other things we can
access/do via the document object:
Get the links on a page.
Alter images on the page
Change html contained within a page element
innerHTML Property
This property of the document object allows you to directly view and modify the
HTML present inside the document.
Though deprecated, this property is still available to HTML-5 and is present in a
lot of legacy code. However, there are better ways of modifying HTML content
(e.g. via node access, via jQuery's html() function, and others).
<script>
function go() {
alert("Check out the text, then click the okay button");
document.getElementById('click').innerHTML = "<h1>Some H1 Text</h1>";
}
</script>
<div id="click" onclick="go()">
<h2>Click Me</h2>
</div>
document Object example
Here is a code example in which we access the 'links' property of
the document object. This property retrieves all of the anchor <a>
tags as a collection. We will then extract all of the URLs from those
<a> elements and output them as an ordered list:
var links = "";
for (var i = 0; i < document.links.length; i++) {
links = links + "<li>" + document.links[i].href + "</li>";
}
document.write("<ol>");
document.write(links);
document.write("</ol>");
Examples: document_object_links.htm
Nodes
The W3C’s specification for the DOM works by describing a web
document as a series of “nodes”.
A web page’s DOM is essentially, a ‘tree’ in which there are
parents, children, siblings, and so on.
The easiest way to see how all of this plays out is probably by
example. We will first open up a document to view the HTML. We
will then use a ‘DOM Inspector’ to see the visual representation of
the DOM as a collection of nodes.
Most browsers have some form of DOM Inspector built in, or
available via plug-ins.
Nodes
<html>
<head>
<title>Page as Tree</title>
</head>
<body>
<div id="div1">
<!-- paragraph one -->
<p>To better understand the document tree,
consider a web page that has a head and body
section, a page title, and the body contains a
div element that itself contains a header and
two paragraphs. One of the paragraphs contains
<i>italicized text</i>; the other has an
image.</p>
<!-- paragraph two -->
<p>Second paragraph with image. <br>
<img src="washington.jpg" alt="Painting of
Washington"/></p>
</div>
</body>
</html>
Firefox's DOM
Inspector
Node Properties inherited from 'Node'
Every Node object has a series of properties and methods
courtesy of a DOM object called 'Node'. These include:
nodeName, nodeValue, nodeType
parentNodes, childNodes
firstChild, lastChild
previousSibling, nextSibling
attributes
ownerDocument
namespaceURI
prefix
localName
Example: node_object_properties.htm
We have just looked at some properties available to nodes
courtesy of the object 'Node'. Every node has an additional
series of properties and methods courtesy of another DOM
object called 'Element'. These include:
getAttribute(name);
setAttribute(name, value);
removeAttribute(name);
getAttributeNode(name);
setAttributeNode(attr);
removeAttributeNode(attr);
hasAttribute(name);
Node Properties inherited from Element'
Example: node_element_properties.htm

More Related Content

Similar to DOM and BOM Guide

INTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGINTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGProf Ansari
 
The Future of the Web
The Future of the WebThe Future of the Web
The Future of the WebRay Nicholus
 
12. session 12 java script objects
12. session 12   java script objects12. session 12   java script objects
12. session 12 java script objectsPhúc Đỗ
 
Modular javascript
Modular javascriptModular javascript
Modular javascriptZain Shaikh
 
Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web TechnologiesPerttu Myry
 
Android Development with Flash Builder Burrito
Android Development with Flash Builder BurritoAndroid Development with Flash Builder Burrito
Android Development with Flash Builder BurritoJeff Bollinger
 
Java script Advance
Java script   AdvanceJava script   Advance
Java script AdvanceJaya Kumari
 
Internet and Web Technology (CLASS-6) [BOM]
Internet and Web Technology (CLASS-6) [BOM] Internet and Web Technology (CLASS-6) [BOM]
Internet and Web Technology (CLASS-6) [BOM] Ayes Chinmay
 
01 Introduction - JavaScript Development
01 Introduction - JavaScript Development01 Introduction - JavaScript Development
01 Introduction - JavaScript DevelopmentTommy Vercety
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databindingBoulos Dib
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJsTudor Barbu
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Manykenatmxm
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1Paras Mendiratta
 

Similar to DOM and BOM Guide (20)

INTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGINTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMING
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
The Future of the Web
The Future of the WebThe Future of the Web
The Future of the Web
 
JS basics
JS basicsJS basics
JS basics
 
12. session 12 java script objects
12. session 12   java script objects12. session 12   java script objects
12. session 12 java script objects
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
 
Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web Technologies
 
Android Development with Flash Builder Burrito
Android Development with Flash Builder BurritoAndroid Development with Flash Builder Burrito
Android Development with Flash Builder Burrito
 
Actionview
ActionviewActionview
Actionview
 
Java script Advance
Java script   AdvanceJava script   Advance
Java script Advance
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Week8
Week8Week8
Week8
 
Internet and Web Technology (CLASS-6) [BOM]
Internet and Web Technology (CLASS-6) [BOM] Internet and Web Technology (CLASS-6) [BOM]
Internet and Web Technology (CLASS-6) [BOM]
 
01 Introduction - JavaScript Development
01 Introduction - JavaScript Development01 Introduction - JavaScript Development
01 Introduction - JavaScript Development
 
Jquery 2
Jquery 2Jquery 2
Jquery 2
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 

Recently uploaded

IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

DOM and BOM Guide

  • 1. JAVASCRIPT Document Object Model (DOM) Browser Object Model (BOM)
  • 2. Document Object Model (DOM) Paraphrased from Wikipedia: That which we see as a window displaying a document, the browser program sees as a hierarchical collection of objects. When the browser parses a document, it creates a collection of objects that define the document and detail how it should be displayed. The object the browser creates is known as the document object. The top level of the hierarchy is the window object, which contains the information not only about the document object, but also about the window displaying the document. The DOM applies not only to web browsers, but also to other types of documents you may have heard of such as XML and XHTML. When applied to web browsers, the DOM is sometimes referred to as the browser object model, or BOM.
  • 3. DOM vs BOM Browser Object Model (BOM) – A term sometimes applied to the DOM specifically referring to the browser context. ‘BOM’ is not an “official” standard. In addition, the BOM is notorious for being interpreted differently by different browsers. This has always been a major problem in web development, and is one area rife with cross-browser compatibility issues. However, because we will be discussing the DOM only within the context of using a web browser, you may encounter the use of BOM as well as DOM.
  • 4. DOM The DOM (or BOM) is a set of several common web objects inherited from the browser "context" that are accessible to JavaScript We have already seen a couple of these objects: window document
  • 5. DOM Hierarchy For the time being, you can think of the above objects as special types of variables. These special variables are more accurately called 'objects'. Think of these as variables that have been pre-declared for you. In most cases, these variables already have values. As with variables, we can view and / or modify their values.
  • 6. Inside a ‘window’ object <html> <head> <title>DOM Example</title> </head> <body> <div id="main_content"> <p>A paragraph of content with <i>some text in italics.</i></p> <p>A second paragraph of content. This paragraph also has an image of a <img src="baseball.jpg"> baseball embedded.</p> </div> </body> </html> Every box in this illustration is called a ‘node’. In jQuery we would select all paragraphs on the page with: $('p') In plain JavaScript we would use: window.document.p
  • 7. window Object By 'window' we are referring to the part of the browser that surrounds the HTML document You can use this window object to open new windows (or tabs), close existing windows (or tabs), resize windows, change the status of windows, dealing with frames, working with timers, etc This object is also your handle to access the lower level items in the hierarchy (see previous slide). The window object incudes methods such as alert() and write() (via the 'document' object) that you have seen previously. The window object is implicit: In theory, we should need to write: window.alert() or window.document.write() However, because it is a global object (beyond the scope of this discussion), the ‘window’ reference is implicitly understood and, therefore, typing out window turns out to be optional.
  • 8. Example: Accessing your images via the DOM window.document.images In jQuery: $('img')
  • 9. Accessing Elements by 'id' <img src=“firetruck.jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”> <img src=“baseball.jpg” id=“ball_pic” name=“baseball” alt=“pic of baseball”> An element can be accessed by its 'id' attribute (if it has one): alert( document.getElementById('firetruck').alt ); //Outputs: ‘pic of truck’
  • 10. Accessing Elements by 'name' <img src=“firetruck.jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”> <img src=“baseball.jpg” id=“ball_pic” name=“baseball” alt=“pic of baseball”> An element can be accessed by its 'name' attribute (if it has one): alert( document.images.firetruck.alt ); //Outputs: ‘pic of truck’ Note that in this case we retrieve all images, and then use the name attribute to indicate which particular image we want to access.
  • 11. Accessing Elements by array <img src=“firetruck.jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”> <img src=“baseball.jpg” id=“ball_pic” name=“baseball” alt=“pic of baseball”> You can access an element using array notation: alert( document.images[0].alt ); //Outputs 'pic of truck' alert( document.images[1].alt ); //Outputs 'pic of ball' That is, document.images selects all images in the document. This is analogous to jQuery's: $('img') Array notation is simply a way to refer to the items in the numerical order in which they appear. Note that array notation begins at 0.
  • 12. Who cares? Are you impressed yet? Okay, I agree that having all of these different ways of accessing things may not seem useful. In addition, the fact that jQuery seems to make it all so much easier. Patience, grasshopper: Over time in your web-development lives, you will see that there are situations where the DOM is preferable – even necessary. In addition, there will be times when you will find that the particular techniques of accessing elements each have their strengths.
  • 13. dom_example.htm <html> <head> <title>DOM Example</title> <script type="text/javascript"> function domTest(){ var images = document.images; //Recall that 'window' is implicit var str="List of Alt Values:n"; for (var i=0; i<images.length; i++) { //this is called a 'loop' str += images[i].alt + "n"; } alert(str); } //end domTest() </script> </head> <body onload="domTest()"> <p>Some smiley-face balls:</p> <img src="blue_ball.jpg" alt="Pic of blue ball" height="80" width="80"> <img src="green_ball.jpg" alt="Pic of green ball" height="80" width="80"> <img src="red_ball.jpg" alt="Pic of red ball" height="80" width="80"> </body> </html>
  • 14. Examples using pop-up windows window.alert() alert(“This is a message”); window.confirm()  Returns a boolean:  True – if user clicks ‘OK’  False – if user clicks ‘Cancel’  Example: var result = confirm(“Continue ?”); window.prompt() Returns the String entered by the user, if the user clicks ‘OK’ Returns ‘null’ if the user clicks ‘Cancel’ var response = prompt(“Your Name ?”, [default] ); Don't forget that even though these methods are part of the 'window' object, the reference to 'window' is "implicit" (i.e. it's presence is assumed). Therefore for clarity, we typically just leave it out.
  • 15. Opening a new browser window To open a window (or tab) use: window.open(arg1, arg2, arg3); All 3 arguments are optional, All 3 take Strings as their data types arg1 - the URL of the document arg2 - window name (for purposes of referencing if needed) – Note: This is not the <title> of the window arg3 - window options to control the appearance of the window. This is where you indicate all desired options (in one single string, separated by commas). Not all options are always available. The options available to you depend on the context. Example: window.open("http://google.com", "", "height=600, width=400, toolbar=no");
  • 16. window.open("http://google.com", "googWin", "height=600, width=400, toolbar=no"); window.open("http://google.com", "googWin", "height=600, width=400, toolbar=yes");
  • 19. Opening a new browser window var newWindow = window.open("", "winInfo", "height=200, width=400"); newWindow.document.write('The current date is: ' + Date() + '<br>'); newWindow.document.write('<input type="button" value="Greet Me" onclick="alert('hi')">'); • Note how this time, we need to include the reference to the current window object, 'newWindow' in order to ensure that our code applies to the appropriate window • Note the advantage of keeping single and double quotes separate • Note the need to use escape characters in the 'onclick' attribute
  • 20. JavaScript API This is a good time to ask ourselves where to find the JavaScript API. There are several resources on the web that provide this information. One we will check out here is provided by the folks at Mozilla: https://developer.mozilla.org/en-US/docs/Web/JavaScript
  • 21. window.open() API from W3 Schools http://www.w3schools.com/jsref/met_win_open.asp Note the need for a 'Browser Support' section.
  • 23. frames Object The frames object has the following properties: parent length name The parent (frameset) can access the children frames by their names. The children can access the other child by going through the parent. Frames are no longer popular – in fact, their use has fallen out of favor and rarely recommended. They are discussed here simply for completeness and because it is possible you will encounter them in legacy code.
  • 25. location Object alert( window.location.href ); //outputs the current URL Recall: alert( location.href ) would also work…
  • 26. location Object A URL such as: http://learning.javascript.info/ch09-01.htm?a=1 Can be broken down into the following property values of the 'location' object: host/hostname: learningjavascript.info protocol: http: search: ?a=1 href: http://learning.javascript.info/ch09-01.htm?a=1 e.g. alert( window.location.protocol ); //outputs ‘http:’
  • 27. Timing Events It is possible to time events using JavaScript. There are two functions in particular that can be useful: setTimeout() and setInterval(). setInterval() will execute a function that you name over and over again at specified intervals (e.g. every 3 seconds). Of course, you will then need a way to stop the execution. This is not difficult, but requires some extra code that we will not get into just now. setTimeout() will execute a function once, after a certain time interval has passed. Both of these methods are part of the ‘window’ object, in exactly the same way that alert() is a method of the window object.
  • 28. //Example: set_timeout_example.htm <html> <head> <title>setTimeout() Example</title> <script type="text/javascript"> function go() { alert('Ready? Click the okay button, then wait 2 seconds to be greeted.'); //After the user closes the alert box above, we wait 2 seconds //and then the greetUser() function is invoked setTimeout("greetUser()",2000); } function greetUser() { alert('Hello!!!'); } </script> </head> <body onload="go()"> </body> </html>
  • 30. navigator Object Allows you to find out information about the client (e.g. web browser or other agent) that is accessing your page. Items you can check for / about include: • The type of browser and related information ('userAgent') • The version number ('appVersion') • Whether cookies are enabled ('cookieEnabled') • The OS on which the client is running ('platform') • Which plug-ins are installed ('plugins') • This is a common technique by which your smartphone is redirected to a 'small-screen friendly' version of a web page
  • 31. 'navigator' object properties Property Description appCodename name of the browser code base appName name of the browser code base appMinorVersion browser minor version appVersion browser major version platform platform that browser is on plugins array of plugins supported userAgent full agent description for browser userLanguage language supported by browser Example: history_navigator_properties.htm
  • 32. history_navigator_properties.htm as run on a Windows desktop computer
  • 35. document Object We have now gone through several of the properties of the window object, albeit somewhat briefly. We will now return to one object with which we are already somewhat familiar, the document object. Of all the objects encapsulated by the window object, the document object is one JS programmers interact with frequently. The document object provides access to any element on the page, either individually or as a collection (e.g. a specific image, or an array of all of the images). We've already seen a few properties/methods: getElementById, getElementByTagName and writeln. Other things we can access/do via the document object: Get the links on a page. Alter images on the page Change html contained within a page element
  • 36. innerHTML Property This property of the document object allows you to directly view and modify the HTML present inside the document. Though deprecated, this property is still available to HTML-5 and is present in a lot of legacy code. However, there are better ways of modifying HTML content (e.g. via node access, via jQuery's html() function, and others). <script> function go() { alert("Check out the text, then click the okay button"); document.getElementById('click').innerHTML = "<h1>Some H1 Text</h1>"; } </script> <div id="click" onclick="go()"> <h2>Click Me</h2> </div>
  • 37. document Object example Here is a code example in which we access the 'links' property of the document object. This property retrieves all of the anchor <a> tags as a collection. We will then extract all of the URLs from those <a> elements and output them as an ordered list: var links = ""; for (var i = 0; i < document.links.length; i++) { links = links + "<li>" + document.links[i].href + "</li>"; } document.write("<ol>"); document.write(links); document.write("</ol>"); Examples: document_object_links.htm
  • 38. Nodes The W3C’s specification for the DOM works by describing a web document as a series of “nodes”. A web page’s DOM is essentially, a ‘tree’ in which there are parents, children, siblings, and so on. The easiest way to see how all of this plays out is probably by example. We will first open up a document to view the HTML. We will then use a ‘DOM Inspector’ to see the visual representation of the DOM as a collection of nodes. Most browsers have some form of DOM Inspector built in, or available via plug-ins.
  • 39. Nodes <html> <head> <title>Page as Tree</title> </head> <body> <div id="div1"> <!-- paragraph one --> <p>To better understand the document tree, consider a web page that has a head and body section, a page title, and the body contains a div element that itself contains a header and two paragraphs. One of the paragraphs contains <i>italicized text</i>; the other has an image.</p> <!-- paragraph two --> <p>Second paragraph with image. <br> <img src="washington.jpg" alt="Painting of Washington"/></p> </div> </body> </html>
  • 41. Node Properties inherited from 'Node' Every Node object has a series of properties and methods courtesy of a DOM object called 'Node'. These include: nodeName, nodeValue, nodeType parentNodes, childNodes firstChild, lastChild previousSibling, nextSibling attributes ownerDocument namespaceURI prefix localName Example: node_object_properties.htm
  • 42. We have just looked at some properties available to nodes courtesy of the object 'Node'. Every node has an additional series of properties and methods courtesy of another DOM object called 'Element'. These include: getAttribute(name); setAttribute(name, value); removeAttribute(name); getAttributeNode(name); setAttributeNode(attr); removeAttributeNode(attr); hasAttribute(name); Node Properties inherited from Element' Example: node_element_properties.htm