Chap4 DOM

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 50

1

Faculty of
Computer and
Information
Sciences
Information Technology
Department
Web Systems and
Technologies
IT 481 T

Lecture 4: Host Objects:


Browsers and the DOM

2
Overview
• The Document Object Model (DOM) is an application
programming interface (API) for HTML and XML documents
• It represents the page so that programs can change the
document structure, style and content.
• W3C (World Wide Web Consortium) recommendations define
standard DOM

3
Overview
• A Web page is a document
• The Document Object Model (DOM)
represents that document so it can be
manipulated.
• The DOM is an object-oriented representation
of the web page, which can be modified with a
scripting language such as JavaScript.

4
Document representation
• Every element in a document—the document
as a whole, the head, the body, tables,
paragraphs—is part of the document object
model for that document
 they can all be accessed and manipulated
using the DOM and a scripting language like
JavaScript and Python.

5
The HTML DOM Tree of Objects

6
DOM and scripting languages
• The DOM was designed to be independent of
any particular programming language
• Though we focus exclusively on JavaScript in
this lecture, implementations of the DOM can
be built for any language
• Python example:
import xml.dom.minidom as m
doc = m.parse("C:\\Projects\\Py\\chap4.xml");
p_list = doc.getElementsByTagName("para");

7
DOM and Javascript
Example: it is written in JavaScript, but it uses the DOM to
access the document and its elements.
var paragraphs = document.getElementsByTagName("p");
// paragraphs[0] is the first <p> element
// paragraphs[1] is the second <p> element, etc.
//typeof paragraphs : object
paragraphs[0].innerHTML="it 481";

 The DOM is not a programming language (it is an interface)


but without it, the JavaScript language wouldn't have any
model or notion of web pages and their component parts
 The page content is stored in the DOM and may be accessed
and manipulated via JavaScript 8
<p> hello </p>
<p> world</p>

hello
<p> hello </p>
world <p> world</p>

<script>
Execute the script 
var paragraphs =
document.getElementsByTagName("p");
it 481 paragraphs[0].innerHTML="it 481";
world </script>

9
HTML DOM
• HTML DOM 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

10
Finding HTML Elements
Properties
Property Description
document.anchors Returns all <a> elements that have a name
attribute
document.body Returns the <body> element
document.forms Returns all <form> elements
document.head Returns the <head> element
document.images Returns all <img> elements
document.links Returns all <a> elements that have a href
attribute
document.scripts Returns all <script> elements
document.title Returns the <title> element
document.URL Returns the complete URL of the document

11
Example
<a name="plants">Plants</a>

write the Javascript code that changes the display from Plants to Veggies, using document
property.

<script>

document.anchors[0].innerHTML='Veggies'; </script>

And not

document.getElementsbyTagName("a'')[0].innerHTML='Veggies';

<a name="plants">Plants</a>

<script>

document.anchors[0].innerHTML='Veggies';
document.getElementsByTagName("a")[0].innerHTML='Veggie';</script>
12
Finding HTML Elements
Methods (1/2)
Method Description

document.getElementById (id) Finds an element by element id

document.getElementsByTagName Finds elements by tag name (div, p,


(name_of_the_element) form ….)

document.getElementsByClassName Finds elements by class name


(name_of_the_class)

document.getElementsByName(nam Finds of elements with a specified


e_attribute) name
<div class=bold> </div>
<p class=bold> hi</p>

<script>
document.getElementsByClassName("bold")[0].innerHTML="hello";
</script>
13
Finding HTML Elements
Methods (2/2)
Method Description
document.querySelector(CSS selectors) returns the first element that matches a
CSS selectors.
document.querySelectorAll(CSS returns all elements that matches a CSS
selectors) selector(s).

For multiple selectors, separate each selector with a comma

14
<!DOCTYPE html>
<html>
<body>
<h2>The querySelectorAll Method</h2>

<p>Add a background color all elements with class="example":</p>


<h2 class="example">A heading</h2>
<p class="example">A paragraph.</p>

<script>
nodeList = document.querySelectorAll(".example");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = « lightblue";
}
</script>

</body>
</html>

15
NodeList vs. HTMLCollection
• A NodeList and an HTMLcollection is very much the same thing.
• Both are array-like collections (lists) of nodes (elements)
extracted from a document.
• Both have a length property that returns the number of
elements in the list (collection).
• An HTMLCollection is a collection of document elements.
• A NodeList is a collection of document nodes (element nodes,
attribute nodes, and text nodes).
• HTMLCollection items can be accessed by their name, id, or
index number.
• NodeList items can only be accessed by their index number.

16
Who Returns a NodeList?

The getElementsByClassName() and


getElementsByTagName() methods return
HTMLCollection

The querySelectorAll() and


getElementsByName() methods returns a NodeList.

17
Changing HTML Elements
Method & 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 (name, src, type, id …. )

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


element (name, src, type, id …. )

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

<input type=text name=inp1>


<script>
document.getElementsByTagName("input")[0].type="file";
document.getElementsByTagName("input")["inp1"].setAttribute("type", "file");

</script>
18
<!DOCTYPE html>
<html> We can use
<body> name=frm1
<form id="frm1">
First name: <input type="text" name="fname" value=Donald><br>
<input type="submit" value="Submit"> </form>
<button onclick="myFunction()">Try it</button>
<p id="demo">hello </p>

<script> function myFunction() {


var x = document.forms["frm1"]; // document.write(typeof x); object
//we can also use document.forms[0];
var text = "";
var i; // is undefined
for (i = 0; i < x.length ;i++) {
text = text+ x.elements[i].value + "<br>"; }
document.getElementById("demo").innerHTML = text;}
</script> </body> </html>
19
<!DOCTYPE html>
<html>
<body>
<form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value=“Donald"><br>
<input type="submit" value="Submit"> </form>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script> function myFunction() {


var x = document.forms["frm1"]; finds the form element with id="frm1“
var text = ""; The variable x holds the form
var i;
for (i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>“; }
document.getElementById("demo").innerHTML = text;}
</script> </body> </html>

20
<!DOCTYPE html>
<html>
<body>
<form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value=“Donald"><br>
<input type="submit" value="Submit"> </form>
<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>“; } Returns the value of each element of the form
document.getElementById("demo").innerHTML = text;}
</script> </body> </html>

21
22
Create New elements
The createElement() method creates an element node.
The createTextNode() method creates a text node.
The appendChild() method appends a node (element) as
the last child of an element.

<body>
<script>
const h1 = document.createElement("h1");
const textNode = document.createTextNode("Hello World");
h1.appendChild(textNode);
document.body.appendChild(h1);
</script>
</body>

23
Exercice
<!DOCTYPE html>
<html>
<body>
<h1>The Element Object</h1>
<h2>The appendChild() Method</h2>

<ul id="myList">
<li>Coffee</li>
<li>Tea</li>
</ul>

<p>Click "Append" to append an item to the end of the list:</p>

<button onclick="myFunction()">Append</button>
24
• Considering the previous html code, write the
javascript code to add an item called Water to
the list

25
Changing the Value of an Attribute
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementsByTagName("img")[0].src = "landscape.jpg";
//document.images[0].src = "landscape.jpg";
//document.getElementById("myImage").src = "landscape.jpg";

</script>
</body>
</html>

26
Changing HTML Style
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello World!</p>
<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
</script>

<p>The paragraph above was changed by a script.</p>


</body>
</html>

27
Event Handling
• An event is an occurrence of something
potentially interesting to a script:
– Ex: mouseover and mouseout events
• An HTML event attribute is used to specify a
script to be called when an event occurs
– Ex: onmouseover
– Name of attribute is on followed by event name

28
DOM Events (1/3)
Event Description
change The event occurs when the content of a form element, the
selection, or the checked state have changed (for <input>,
<select>, and <textarea>)

click The event occurs when the user clicks on an element

copy The event occurs when the user copies the content of an
element
dblclick The event occurs when the user double-clicks on an element

29
DOM Events (2/3)
Event Description
keydown The event occurs when the user is pressing a key
keyup The event occurs when the user releases a key
load The event occurs when an object has loaded
mousedown The event occurs when the user presses a mouse button over an
element
Mouseleave The event occurs when the pointer is moved out of an element
Mouseout
Mouseover The event occurs when the pointer is moved onto an element,
or onto one of its children

30
DOM Events (3/3)
Event Description
Paste The event occurs when the user pastes some content in an
element
Pause The event occurs when the media is paused either by the user or
programmatically
Play The event occurs when the media has been started or is no
longer paused
Resize The event occurs when the document view is resized

reset The event occurs when a form is reset


submit The event occurs when a form is submitted

31
Assign Events Using the HTML DOM
<!DOCTYPE html> <html>
<body onload="checkCookies()">

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

<script>
function checkCookies() {
var text = "";
if (navigator.cookieEnabled == true) {
text = "Cookies are enabled.";
} else {
text = "Cookies are not enabled.";
}
document.getElementById("demo").innerHTML = text;
}
</script></body></html>

32
Assign Events Using the HTML DOM
<!DOCTYPE html> <html>
<body onload="checkCookies()">
The load event
<p id="demo"></p>

<script>
function checkCookies() {
var text = "";
if (navigator.cookieEnabled == true) {
text = "Cookies are enabled.";
} else {
text = "Cookies are not enabled.";
}
document.getElementById("demo").innerHTML = text;
}
</script></body></html>

33
The onchange Event
<!DOCTYPE html><html>
<head>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script> </head>
<body>

Enter your name: <input type="text" id="fname" onchange="myFunction()">


</body> </html>

34
The onchange Event

The onchange event is often used in combination with validation of input fields.

35
Object hierarchy
The window is the root element in DOM

36
Window Object - Properties
Property Description
closed Returns a Boolean value indicating whether a window has been
closed or not

document Returns the Document object for the window


innerHeight Returns the inner height of a window's content area
innerWidth Returns the inner width of a window's content area
location Returns the Location object for the window : information about
the current URL.

name Sets or returns the name of a window


navigator Returns the Navigator object for the window (contains
information about the browser)

37
Property Description
outerHeight Returns the outer height of a window, including toolbars/scrollbars
outerWidth Returns the outer width of a window, including toolbars/scrollbars
screen Returns the Screen object for the window
screenX Returns the horizontal coordinate of the window relative to the screen

screenY Returns the vertical coordinate of the window relative to the screen

38
Window Object - Methods
Method Description
alert() Displays an alert box with a message and an OK button
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
moveTo() Moves a window to the specified position
moveBy() moves a window a specified number of pixels relative to its current coordinates.
open() Opens a new browser window
window.open(URL, name, specs, replace)
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
resizeTo() Resizes the window to the specified width and height
resizeBy() resizes a window by the specified amount, relative to its current size.
scrollTo() Scrolls the document to the specified coordinates
window.scrollTo(xpos, ypos)
scrollBy() scrolls the document by the specified number of pixels.
window.scrollBy(xnum, ynum)
stop() Stops the window from loading

The prompt() method returns the input value if the user clicks "OK« as a string 39
<!DOCTYPE html>
<html>
<body>
<p id=text >The content of the body element is displayed
in your browser.</p>
</body>
<script>
var x = prompt();
document.getElementById("text").innerHTML=x;
</script>
</html>
40
<!DOCTYPE html>
<html>

<style>
body {width: 5000px}
button {position:fixed}
</style>

<body>

<p>Look at the horizontal scrollbar to see the effect.</p>

<button onclick="window.scrollBy(100, 0);">click me to scroll horizontally!</button>

</body>
</html>
41
42
ent

43
44
Error Reference

• The try statement defines a


code block to run (to try).
• The catch statement defines
a code block to handle any
error.
• The finally statement
defines a code block to run
regardless of the result.
• The throw statement
defines a custom error.

45
Error Names
Error Name Description
RangeError A number "out of range" has occurred
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
URIError An error in encodeURI() has occurred

46
ReferenceError
<p>You cannot use the value of a non-existing variable:</p>

<p id="P1"></p>

<script>
let x = 5;
try {
x = y + 1;
}
catch(err) {
document.getElementById("P1").innerHTML = err.name;
}
</script>
47
TypeError
<p id="demo"></p>
<script>
let x=10;
try {

document.getElementByID("demo").innerHTML =x;

}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
</script>
48
Book Chapter/ References:
Web Technologies: A Computer Science
Perspective by Jeffrey C. Jackson, Pearson
Education, chap 5 p. 249-300
THANK
YOU

You might also like