06-Dom & Bom

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

4/27/2015

Document Object Model

Accessing HTML Elements


using JavaScript

What is the DOM?


 When a web page is loaded, the browser creates a Document
Object Model of the page.
 The DOM is a W3C (World Wide Web Consortium) standard.
 The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-


neutral interface that allows programs and scripts to dynamically access
and update the content, structure, and style of a document.“

 The W3C DOM standard is separated into 3 different parts:


 Core DOM - standard model for all document types.
 XML DOM - standard model for XML documents.
 HTML DOM - standard model for HTML documents.

1
4/27/2015

What is the HTML DOM?


 The HTML DOM is a standard object model and
programming interface for HTML.
 It defines :
 The HTML elements as objects.
 The properties of all HTML elements.
 The methods to access all HTML elements.
 The events for all HTML elements.
 In other words: The HTML DOM is a standard for
how to get, change, add, or delete HTML elements.
 With the HTML DOM, JavaScript can access and
change all the elements of an HTML document.

The DOM Programming


Interface
 The HTML DOM can be accessed with JavaScript
(and with other programming languages).
 In the DOM, all HTML elements are defined as
objects.
 The programming interface is the properties and
methods of each object.
 A property is a value that you can get or set (like
changing the content of an HTML element).
 A method is an action you can do (like add or
deleting an HTML element).

2
4/27/2015

The HTML DOM Document

 In the HTML DOM object model, the


document object represents your web
page.
 The document object is the owner of
all other objects in your web page.
 If you want to access objects in an
HTML page, you always start with
accessing the document object.

HTML DOM Elements

 Often, with JavaScript, you want to


manipulate HTML elements in a document.
 To do so, you have to find the elements first.
 There are a couple of ways to do this:
 Finding HTML elements by id.
 Finding HTML elements by tag name.
 Finding HTML elements by class name.
 Finding HTML elements by CSS selectors.
 Finding HTML elements by HTML object
collections.

3
4/27/2015

Finding HTML Element by Id

 The easiest way to find an HTML element in


the DOM, is by using the element id.
 This is done using
document.getElementById() method.
 The parameter denotes the id of the
element to be found.
 If the element is found, the method will
return the element as an object, else it will
return null.

Finding HTML Elements by


Tag Name

 If you want to find all HTML elements with


the same type, use
document.getElementsByTagName().
 The parameter denotes the type of elements
(tag name) to be found.
 If elements are found, the method will return
all the elements as an array of objects, else
it will return null.

4
4/27/2015

Finding HTML Elements by


Class Name

 If you want to find all HTML elements with


the same class name, use
document.getElementsByClassName().
 The parameter denotes the class name of
elements to be found.
 If elements are found, the method will return
all the elements as an array of objects, else
it will return null.

Finding HTML Elements by


CSS Selectors
 If you want to find all HTML elements that matches
a specified CSS selector (id, class names, types,
attributes, values of attributes, etc), use the
document.querySelectorAll() method.
 The parameter denotes the CSS Selector (i.e.
p.demo) of elements to be found.
 If elements are found, the method will return all the
elements as an array of objects, else it will return
null.
 Note that the querySelectorAll() method does
not work in Internet Explorer 8 and earlier versions.

5
4/27/2015

Finding HTML Elements by


HTML Object Collections
 The DOM Document has several collections that
contain object that can be accessed using index :
 document.anchors
 document.body
 document.documentElement
 document.embeds
 document.forms
 document.head
 document.images
 document.links
 document.scripts
 document.title

Changing HTML Content


 The easiest way to modify the content of an HTML
element is by using the innerHTML property.
 To change the content of an HTML element, use this
syntax:
document.getElementById(id).innerHTML = new HTML

 Example :
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>

6
4/27/2015

Changing the Value of an


Attribute

 To change the value of an HTML attribute,


use this syntax:
document.getElementById(id).attribute=new value

 Example :
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src =
"landscape.jpg";
</script>
</body>

Changing HTML Style


 To change the style of an HTML element, use this
syntax:
document.getElementById(id).style.property =
new style
 Example :
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color =
"blue";
</script>
</body>

7
4/27/2015

Changing HTML Visibility

 Changing the visibility of HTML


elements can be done using :
 visibility property
 display property

Examples
<body>
<img src="http://oi44.tinypic.com/30u3e52.jpg" id="pic1" />
<br>
<input type="button" value="Ship" onclick="sh()" />&nbsp;
<input type="button" value="Plane" onclick="pl()" />&nbsp;
<input type="button" value="Hide" onclick="h()" />&nbsp;
<input type="button" value="Show" onclick="s()" />&nbsp;
<script type="text/javascript">
var x=document.getElementById("pic1");
function sh() { x.src="http://oi44.tinypic.com/9te69k.jpg"; return; }
function pl() { x.src="http://oi44.tinypic.com/30u3e52.jpg"; return; }
function h() { x.style.display="none"; return; }
function s() { x.style.display="inline"; return; }
</script>
</body>

8
4/27/2015

Reacting to Events

 A JavaScript can be executed when an


event occurs.
 To execute code when a user clicks on
an element, add JavaScript code to an
HTML event attribute.
 Example :
<button onclick="displayDate()">Try it</button>

Assign Events Using the


HTML DOM

 The HTML DOM allows you to assign


events to HTML elements using
JavaScript.
 Example :
<button id="myBtn">Show Date</button>
<script>
document.getElementById("myBtn").onclick =
displayDate;
</script>

9
4/27/2015

DOM Nodes
 According to the W3C HTML DOM standard,
everything in an HTML document is a node, that is :
 The entire document is a document node.
 Every HTML element is an element node.
 The text inside HTML elements are text nodes.
 Every HTML attribute is an attribute node.
 All comments are comment nodes.
 With the HTML DOM, all nodes in the node tree can
be accessed by JavaScript.
 New nodes can be created, and all nodes can be
modified or deleted.

Node Relationships

 The nodes in the node tree have a


hierarchical relationship to each other.
 The terms parent, child, and sibling are
used to describe the relationships.
 In a node tree, the top node is called the root (or
root node).
 Every node has exactly one parent, except the
root (which has no parent).
 A node can have a number of children.
 Siblings (brothers or sisters) are nodes with the
same parent.

10
4/27/2015

Navigating Between Nodes


 You can use the following node properties
to navigate between nodes with JavaScript:
 parentNode
 childNodes[nodenumber]
 firstChild
 lastChild
 nextSibling
 previousSibling
 The value of the text node can be accessed
by the node's innerHTML property, or the
nodeValue.

The nodeName Property


 The nodeName property specifies the name of a
node.
 nodeName is read-only.
 nodeName of an element node is the same as the
tag name.
 nodeName of an attribute node is the attribute name.
 nodeName of a text node is always #text.
 nodeName of the document node is always
#document.
 Note: nodeName always contains the uppercase tag
name of an HTML element.

11
4/27/2015

The nodeValue Property

 The nodeValue property specifies the


value of a node.
 nodeValue for element nodes is
undefined.
 nodeValue for text nodes is the text
itself.
 nodeValue for attribute nodes is the
attribute value.

The nodeType Property

 The nodeType property returns the


type of node.
 nodeType is read only.
 The most important node types are:

12
4/27/2015

Creating New HTML Elements


(Nodes)
 To add a new element to the HTML DOM, you must
create the element (element node) first, and then
append it to an existing element.
 Example :
<div id="div1">
<p id="p1">This is a paragraph.</p>
</div>
<script>
var p = document.createElement("p");
var n = document.createTextNode("This is new.");
p.appendChild(n);
var e = document.getElementById("div1");
e.appendChild(p);
</script>

Creating new HTML Elements


- insertBefore()
 The appendChild() method appended the new element as
the last child of the parent.
 If you don't want that you can use the insertBefore()
method.
 Example :
<div id="div1">
<p id="p1">This is a paragraph.</p>
</div>
<script>
var p = document.createElement("p");
var n = document.createTextNode("This is new.");
p.appendChild(n);
var e = document.getElementById("div1");
var c = document.getElementById("p1");
e.insertBefore(p,c);
</script>

13
4/27/2015

Removing Existing HTML


Elements
 To remove an HTML element, you must know the
parent of the element, using removeChild() at
that parent.
 Example :
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is a another paragraph.</p>
</div>
<script>
var e = document.getElementById("div1");
var c = document.getElementById("p1");
e.removeChild(c);
</script>

Replacing HTML Elements


 To replace an element to the HTML DOM, use the
replaceChild() method.
 Example :
<div id="div1">
<p id="p1">This is a paragraph.</p>
</div>
<script>
var p = document.createElement("p");
var n = document.createTextNode("This is new.");
p.appendChild(n);
var e = document.getElementById("div1");
var c = document.getElementById("p1");
e.replaceChild(p,c);
</script>

14
4/27/2015

Examples
<body>
<h1>Name Validator</h1>
<label for="n1">Please enter your name : </label>
<input type="text" id="n1" length="40" /><br>
<input type="button" value="Validate" onclick="pl()" />
<script type="text/javascript">
var x=document.getElementById("n1");
function pl(){
var y=x.value;
y=y.replace(/[0-9]/gi, "");
y=y.replace(/\u0027/gi, "`");
x.value=y;
}
</script>
</body>

The Browser Object Model


(BOM)

 The Browser Object Model (BOM)


allows JavaScript to "talk to" the
browser.
 There are no official standards for the
Browser Object Model (BOM).

15
4/27/2015

The Window Object


 The window object is supported by all browsers. It
represent the browser's window.
 All global JavaScript objects, functions, and
variables automatically become members of the
window object.
 Global variables are properties of the window
object.
 Global functions are methods of the window object.
 Even the document object (of the HTML DOM) is a
property of the window object.

Window Size
 Three different properties can be used to determine the size of
the browser window (NOT including toolbars and scrollbars).
 For Internet Explorer, Chrome, Firefox, Opera, and Safari:
 window.innerHeight - the inner height of the browser window
 window.innerWidth - the inner width of the browser window
 For Internet Explorer 8, 7, 6, 5:
 document.documentElement.clientHeight
 document.documentElement.clientWidth
or
 document.body.clientHeight
 document.body.clientWidth

16
4/27/2015

Practical JavaScript solution


var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

Window Methods
 window.open() - open a new window.
 window.close() - close the current window.
 window.alert() - displays a dialog box with a message
and an OK button.
 window.confirm() - displays a dialog box with a message
and an OK and a Cancel button.
 window.prompt() - displays a dialog box that prompts the
visitor for input.
 window.print() - prints the content of the current window.
 window.moveTo() - move the current window.
 window.resizeTo() - resize the current window.
 window.scrollTo() - scrolls the document to the specified
coordinates.

17
4/27/2015

Window open() Method


 The open() method opens a new browser window.
 Syntax :
window.open(URL,name,specs,replace)
 URL – optional, specifies the URL of the page to open. If no URL is
specified, a new window with about:blank is opened.
 Name – optional, specifies the target attribute or the name of the
window. The following values are supported:
 _blank - URL is loaded into a new window. This is default.
 _parent - URL is loaded into the parent frame.
 _self - URL replaces the current page.
 _top - URL replaces any framesets that may be loaded.
 name - the name of the window.
 Specs – optional, a comma-separated list of items.
 Replace – optional, specifies whether the URL creates a new entry or
replaces the current entry in the history list. The following values are
supported:
 true - URL replaces the current document in the history list.
 false - URL creates a new entry in the history list.

Window open()’s specs

18
4/27/2015

Window close() Method

 The close() method closes the


current window.
 This method is often used together
with the open() method.
 Syntax
window.close()

Window alert() Method


 The alert() method displays an alert box with a
specified message and an OK button.
 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.
 The alert box takes the focus away from the current
window, and forces the browser to read the
message. Do not overuse this method, as it
prevents the user from accessing other parts of the
page until the box is closed.
 Syntax :
window.alert(message)

19
4/27/2015

Window confirm() Method


 The confirm() method displays a dialog box with a
specified message, along with an OK and a Cancel button.
 A confirm box is often used if you want the user to verify or
accept something.
 The confirm box takes the focus away from the current
window, and forces the browser to read the message. Do not
overuse this method, as it prevents the user from accessing
other parts of the page until the box is closed.
 The confirm() method returns true if the user clicked "OK",
and false otherwise.
 Syntax :
window.confirm(message)

Window prompt() Method


 The prompt() method displays a dialog box that prompts the
visitor for input.
 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. Do
not overuse this method, as it prevent the user from accessing
other parts of the page until the box is closed.
 The prompt() method returns the input value if the user
clicks "OK". If the user clicks "cancel" the method returns null.
 Syntax :
window.prompt(text,defaultText)

20
4/27/2015

Window print() Method

 The print() method prints the


contents of the current window.
 The print() method opens the Print
Dialog Box, which lets the user to
select preferred printing options.
 Syntax :
window.print()

Window moveTo() Method

 The moveTo() method moves a


window's left and top edge to the
specified coordinates.
 Syntax :
window.moveTo(x,y)

21
4/27/2015

Window resizeTo() Method

 The resizeTo() method resizes a


window to the specified width and
height.
 Syntax :
window.resizeTo(width,height)

Window scrollTo() Method

 The scrollTo() method scrolls the


document to the specified coordinates.
 Syntax
window.scrollTo(xpos,ypos)

22
4/27/2015

Window Screen Object


 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 - returns the width of the visitor's screen in pixels.
 screen.height - returns the height of the visitor's screen in pixels.
 screen.availWidth - returns the width of the visitor's screen, in
pixels, minus interface features like the Windows Taskbar.
 screen.availHeight - returns the height of the visitor's screen, in
pixels, minus interface features like the Windows Taskbar.
 screen.colorDepth - returns the number of bits used to display one
color.
 screen.pixelDepth - returns the pixel depth of the screen.

Window Location Object


 The window.location object can be used to get the current
page address (URL) and to redirect the browser to a new
page.
 The window.location object can be written without the
window prefix.
 Properties and Method :
 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.

23
4/27/2015

Window History Object


 The window.history object contains the
browsers history.
 The window.history object can be written
without the window prefix.
 To protect the privacy of the users, there are
limitations to how JavaScript can access this object.
 Methods:
 history.back() - same as clicking back in the browser
 history.forward() - same as clicking forward in the
browser

Window Navigator Object


 The window.navigator object contains information about the
visitor's browser.
 The window.navigator object can be written without the window
prefix.
 Properties and Method :
 navigator.appName - return the application name of the browser.
 navigator.appCodeName - return the code name of the browser.
 navigator.appVersion - returns version of the browser.
 navigator.cookieEnabled - returns true if cookies are enabled,
otherwise false.
 navigator.language - returns the browser's language.
 navigator.platform - returns the browser platform (operating
system).
 navigator.product - returns the engine name of the browser.
 navigator.userAgent - returns version information about the
browser
 navigator.javaEnabled() - returns true if Java is enabled.

24
4/27/2015

Timing Events
 With JavaScript, it is possible to execute some code
at specified time-intervals. This is called timing
events.
 It's very easy to time events in JavaScript. The two
key methods that are used are:
 setInterval() - executes a function, over and over
again, at specified time intervals.
 setTimeout() - executes a function, once, after waiting
a specified number of milliseconds.
 The setInterval() and setTimeout() are
both methods of the HTML BOM Window object.

The setInterval() Method


 The setInterval() method will wait a specified
number of milliseconds, and then execute a
specified function, and it will continue to execute the
function, once at every given time-interval.
 The window.setInterval() method can be
written without the window prefix.
 The first parameter should be a function.
 The second parameter indicates the length of the
time-intervals between each execution in
miliseconds.
 Syntax :
window.setInterval("javascript function",
milliseconds);

25
4/27/2015

The clearInterval()
Method
 The clearInterval() method is used to stop
further executions of the function specified in the
setInterval() method.
 The window.clearInterval() method can be
written without the window prefix.
 To be able to use the clearInterval() method,
you must use a global variable when creating the
interval method.
 Then you will be able to stop the execution by
calling the clearInterval() method.
 Syntax :
window.clearInterval(intervalVariable)

The setTimeout() Method


 The window.setTimeout() method can be
written without the window prefix.
 The setTimeout() method will wait the specified
number of milliseconds, and then execute the
specified function.
 The first parameter should be a function.
 The second parameter indicates how many
milliseconds, from now, you want to execute the
first parameter.
 Syntax :
window.setTimeout("javascript function",
milliseconds);

26
4/27/2015

The clearTimeout()
Method
 The clearTimeout() method is used to stop the
execution of the function specified in the
setTimeout() method.
 The window.clearTimeout() method can be
written without the window prefix.
 To be able to use the clearTimeout() method,
you must use a global variable when creating the
timeout method.
 Then, if the function has not already been executed,
you will be able to stop the execution by calling the
clearTimeout() method.
 Syntax :
window.clearTimeout(timeoutVariable)

Cookies
 Cookies let you store user information in web pages.
 Cookies are data, stored in small text files, on your computer.
 When a web server has sent a web page to a browser, the
connection is shut down, and the server forgets everything about the
user.
 Cookies were invented to solve the problem "how to remember
information about the user":
 When a user visits a web page, his name can be stored in a cookie.
 Next time the user visits the page, the cookie "remembers" his name.
 Cookies are saved in name-value pairs.
 When a browser request a web page from a server, cookies
belonging to the page is added to the request. This way the server
gets the necessary data to "remember" information about users.

27
4/27/2015

Cookies, cont…
 JavaScript can create, read, and delete cookies
with the document.cookie property, like :
document.cookie="username=John Doe";
 You can also add an expiry date (in UTC time). By
default, the cookie is deleted when the browser is
closed. Example :
document.cookie="username=John Doe; expires=Thu,
18 Dec 2013 12:00:00 UTC";
 With a path parameter, you can tell the browser
what path the cookie belongs to. By default, the
cookie belongs to the current page. Example :
document.cookie="username=John Doe; expires=Thu,
18 Dec 2013 12:00:00 UTC; path=/";

28

You might also like