0% found this document useful (0 votes)
16 views

Lecture 6-Javascript DOM New

The document provides an overview of the Document Object Model (DOM), specifically focusing on the HTML DOM, which is a standard object model and programming interface for HTML. It explains how the DOM allows access and manipulation of HTML elements through properties and methods, and outlines the hierarchical structure of the DOM with various object types. Additionally, it covers event handling in the DOM, including how to assign events and use event listeners in JavaScript.

Uploaded by

shahirah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lecture 6-Javascript DOM New

The document provides an overview of the Document Object Model (DOM), specifically focusing on the HTML DOM, which is a standard object model and programming interface for HTML. It explains how the DOM allows access and manipulation of HTML elements through properties and methods, and outlines the hierarchical structure of the DOM with various object types. Additionally, it covers event handling in the DOM, including how to assign events and use event listeners in JavaScript.

Uploaded by

shahirah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

LECTURE 6

JAVASCRIPT HTML DOM


The Document Object Model
(DOM)
What is the DOM?
• 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
The HTML DOM
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
• When a web page is loaded, the browser creates a Document Object
Model of the page
• Every element on an HTML page is accessible in JavaScript through
the DOM
• The HTML DOM is a standard for how to get, change, add, or delete
HTML elements
• The HTML DOM is platform and language independent
• can be used by any programming language like Java, JavaScript, and VBScript
What is 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.
• HTML DOM methods are actions you can perform (on
HTML Elements).
• HTML DOM properties are values (of HTML Elements)
that you can set or change.
The HTML DOM (Document Object Model)
• The HTML DOM model is constructed as a tree of Objects.
• The Objects are organized in a hierarchy.

Window object − Top of the hierarchy. It is the


outmost element of the object hierarchy.
Document object − Each HTML document that
gets loaded into a window becomes a
document object. The document contains the
contents of the page.
Form object − Everything enclosed in the
<form>...</form> tags sets the form object.
Form control elements − The form object
contains all the elements defined for that
object such as text fields, buttons, radio
buttons, and checkboxes.

A simple hierarchy of a few important objects.


HTML DOM Objects
• Document object
• Event object
• Form and Form Input object
• Anchor object
• Frame, Frameset, and IFrame objects
• Image object
• Location object
• Navigator object
• Option and Select objects
• Screen object
• Table, TableHeader, TableRow, TableData objects
• Window object
HTML DOM Properties and Methods
• The programming interface of the DOM is defined by
standard properties and methods:
• HTML DOM methods are actions you can perform (on
HTML Elements).
• HTML DOM properties are values (of HTML Elements) that
you can set or change.
• For example:
txt=document.getElementById("intro").innerHTML;
getElementById is a method,
while innerHTML is a property.
HTML Document Objects
The HTML DOM Document Object
The node tree below shows an example of a set of nodes of a HTML
document object, and the connections between them.
The tree starts at the root node and branches out to the text nodes at the
lowest level of the tree:

<html>
<head>
<title>My title</title>
</head>

<body>
<a href=“ftmk.html”>My link</a>
<h1>My header</h1>
</body>
</html>
• According to the W3C HTML DOM standard, everything
in an HTML document is a node:
• 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
The HTML DOM: Document Object 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
<html> The HTML document can be read as:
• <html> is the root node
• <html> has no parent
<head>
• <html> is the parent of <head> and
<title>DOM Tutorial • <body>
</title> • <head> is the first child of <html>
</head> • <body> is the last child of <html>
and:
• <head> has one child: <title>
<body>
• <title> has one child (a text node):
<h1>DOM Lesson one</h1> "DOM Tutorial"
<p>Hello world!</p> • <body> has two children: <h1> and
</body> <p>
• <h1> has one child: "DOM Lesson one"
• <p> has one child: "Hello world!"
</html>
• <h1> and <p> are siblings

An Example of A Document Object Node Relationships


DOM Elements
Document Objects: Finding HTML Elements
• to access any element in an HTML page, we always start
with accessing/finding the document object
Method Description
document.getElementById(id) Find an element by element id Try It!
document.getElementsByTagName(name) Find elements by tag name Try It!
document.getElementsByClassName(name) Find elements by class name Try It!
document. querySelectorAll(CSS selector) Find elements by CSS selectors Try It!
document.element[name].elements[i].value Find elements by HTML Object Collections

Try It!
Document Objects: Finding HTML Elements by Id
<html>
<body>
<p id="intro">Hello World!</p>
<p>This example demonstrates the
<b>getElementById</b> method!</p>
<script type="text/javascript">
x=document.getElementById("intro");
document.write("<p>The text from the intro
paragraph: " + x.innerHTML + "</p>");
</script>
</body>
</html>
Finding HTML Elements by Tag Name
<html>
<body>

<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the
<b>getElementsByTagName</b> method.</p>

<script type="text/javascript">
x=document.getElementsByTagName("p");
document.write("Text of first paragraph: " +
x[0].innerHTML);
</script>

</body>
</html>
Finding HTML Elements by Class Name
<!DOCTYPE html>
<html>
<body>

<h2>Finding HTML Elements by Class Name</h2>


<p>Hello World!</p>

<p class="intro">The DOM is very useful.</p>


<p class="intro">This example demonstrates the
<b>getElementsByClassName</b> method.</p>

<p id="demo"></p>

<script>
var x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' +
x[0].innerHTML;
</script>
</body>
</html>
Finding HTML Elements by CSS Selectors
<!DOCTYPE html>
<html>
<body>

<h2>Finding HTML Elements by Query Selector</h2>

<p>Hello World!</p>

<p class="intro">The DOM is very useful.</p>


<p class="intro">This example demonstrates the <b>querySelectorAll</b>
method.</p>

<p id="demo"></p>

<script>
var x = document.querySelectorAll("p.intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with
class="intro": ' + x[0].innerHTML;
</script>

</body>
</html>
Finding HTML Elements by HTML Object Collections
<form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br><br>
<input type="submit" value="Submit">
</form>

<p>Click "Try it" to display the value of each element in the


form.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length ;i++)
{
text += x.elements[i].value +
"<br>";
}
document.getElementById("demo")
DOM HTML
Write Text to the HTML Output Stream

<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html> Try It!
Write Text with Formatting to the Output

<html>
<body>
<script type="text/javascript">
document.write("<h1>Hello World!</h1>");
</script>
</body>
</html>
Changing HTML Content: The innerHTML Property
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript can Change HTML</h2>
<p id="p1">Hello World!</p> Try It!
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
• The easiest way to get the content of an element is by using the innerHTML property.
• The innerHTML property is useful for getting or replacing the content of HTML
elements.
• The innerHTML property can be used to get or change any HTML element, including
<html> and <body>.
JavaScript HTML DOM - Changing CSS

• The HTML DOM allows JavaScript to


change the style of HTML elements.
• To change the style of an HTML element,
use this syntax:
document.getElementById(id).style.property =
new style
DOM Events
HTML DOM - Events
• A JavaScript can be executed when an event
occurs, like when a user clicks on an
HTML element.
• To execute code when a user clicks on an
element, add JavaScript code to an HTML
event attribute:
onclick=JavaScript
23

EVENTS AND EVENT HANDLING


Event Tag Attribute
abort onAbort
blur onBlur
change onChange
click onClick
error onError
focus onFocus
load onLoad
mouseout onMouseOut
mouseover onMouseOver
reset onReset
resize onResize
select onSelect
submit onSubmit
unload onUnload
24

EVENTS AND EVENT HANDLING


• The same attribute can appear in several different tags
– e.g., The onClick attribute can be in <a> and <input>
• A text element gets focus in three ways:
1. When the user puts the mouse cursor over it and presses the left
button
2. When the user tabs to the element
3. By executing the focus method
• Event handlers can be specified in two ways:
1. By assigning the event handler script to an event tag attribute
onClick = "alert('Mouse click!');“
onClick = "myHandler();“
• Example: the load event - triggered when the loading of a
document is completed
Assign Events Using the Event Attributes
To assign events to HTML elements you can use event attributes.
<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the date.</p>

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>

</body>
</html>
Assign Events Using the HTML DOM
The HTML DOM allows you to assign events to HTML
elements
<!DOCTYPE html>
<html>
<body>

<p>Click "Try it" to execute the displayDate() function.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>
document.getElementById("myBtn").onclick = displayDate;

function displayDate()
{ document.getElementById("demo").innerHTML =
Date();
}
</script>

</body>
DOM Event Listener
JavaScript HTML DOM EventListener
• The addEventListener() method attaches an event handler to
the specified element.
• The addEventListener() method attaches an event handler to
an element without overwriting existing event handlers.
• You can add many event handlers to one element.
• You can add many event handlers of the same type to one element, i.e
two "click" events.
• The addEventListener() method makes it easier to control how
the event reacts to bubbling.
• You can add event listeners to any DOM object not only HTML
elements. i.e the window object.
• When using the addEventListener() method, the
JavaScript is
separated from the HTML markup, for better readability and allows you
to add event listeners even when you do not control the HTML markup.
• You can easily remove an event listener by using the
removeEventListener() method.
Syntax
element.addEventListener(event,
function, useCapture);
The first parameter is the type of the event (like
"click" or "mousedown").
The second parameter is the function we want to
call when the event occurs.
The third parameter is a boolean value
specifying
whether to use event bubbling or event capturing.
This parameter is optional.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript addEventListener()</h2>

<p>This example uses the addEventListener() method to attach a click


event to a button.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>
document.getElementById("myBtn").addEventListener("click",
displayDate);

function displayDate()
{ document.getElementById("demo").innerHTML =
Date();
}
</script>
</body>
</html>
30

EVENTS AND EVENT HANDLING


<!-- load.html
An example to illustrate the load events
-->
<html>
<head><title> The onLoad event handler></title>
<script type = "text/javascript">
<!--
// The onload event handler
function load_greeting ()
{
alert("You are visiting
the home page of \n"
+ "Pete's Pickled
Peppers \n"
+ "WELCOME!!!");
}
// -->
</script>
</head>
<body
onload="load_greeting();">
31

EVENTS AND EVENT HANDLING


• Radio buttons
<input type = "radio" name = "button_group“ value =
"blue" onClick = "handler()">
– The checked property of a radio button object is true if the button is
pressed
– Can’t use the element’s name to identify it, because all buttons in the
group have the same name
– Must use the DOM address of the element, e.g.,
var radioElement = document.myForm.elements;
– Now we have the name of the array of elements
for (var index = 0; index < radioElement.length;
index++) {
if (radioElement[index].checked)
{ element =
radioElement[index].value; break;
}
}
32

EVENTS AND EVENT HANDLING


2. Event handlers can be specified by assigning them to
properties of the JavaScript objects associated with the
HTML elements
– The property names are lowercase versions of the attribute
names
– If the event handler is a function, just assign its name to the property,
as in
document.myForm.elements[0].onclick =
myHandler;
– This sets the handler for the first element in the form
– This would need to follow both the handler function and the HTML
form
– If this is done for a radio button group, each element of the array must
be assigned
- The disadvantage of specifying handlers by assigning them to event
properties is that there is no way to use parameters
33

EVENTS AND EVENT HANDLING


– The advantage of specifying handlers by assigning them to event
properties are:
1. It is good to keep HTML and JavaScript separate
2. The handler could be changed during use
• Checking Form Input
– A good use of JavaScript, because it finds errors in form input before it
is sent to the server for processing
– Things that must be done:
1. Detect the error and produce an alert message
2. Put the element in focus (the focus function)
3. Select the element (the select function)
– The focus function puts the element in focus, which puts the cursor in
the element
document.getElementById("phone").focus();
– The select function highlights the text in the element
– To keep the form active after the event handler is finished, have it
return false
34

EVENTS AND EVENT HANDLING


• Example – comparing passwords
– If a password will be used later, the user is asked to type it in twice
– The program must verify that the second typing of the password is the
same as the first
– The form just has two password input boxes to get the passwords and
Reset and Submit buttons
– The event handler is triggered by the Submit button
• Handler actions:
1. If no password has been typed in the first box, focus on that box and
return false
2. If the two passwords are not the same, focus and select the first box
and return false. if they are the same, return true
--> SHOW pswd_chk.html
JavaScript BOM (1)
• There are no official standards for
the Browser Object Model (BOM).
• Since modern browsers have implemented
(almost) the same methods and properties
for JavaScript interactivity, it is often
referred to, as methods and properties of
the BOM.
• The BOM provides us with objects that
expose the web browser’s functionality.
JavaScript BOM (2)
• Opening a new browser Window

• Navigating to a different Location:

• Getting information about the user's


browser and device using Navigator object:
JavaScript BOM (3)
• Displaying an alert message:

• Screen: get the information about the screen on


which the browser is running by using Screen object.

• Moving backward or forward in the browser


History:
End of lecture..

You might also like