ITEW2 WEEK 11 Document Object Model Part 1
ITEW2 WEEK 11 Document Object Model Part 1
COURSE INTENDED 1. Design and implement JavaScript codes appropriate to the requirements of the
LEARNING OUTCOMES: programming problem.
2. Write readable JavaScript programs compliant to widely-accepted coding
conventions implementing OOP approach.
3. Create JavaScript programs applying JQuery and Web Storage.
LEARNING MATERIAL
FOR WEEK NUMBER:
11
I. TITLE: DOCUMENT OBJECT MODEL PART 1
III. INTRODUCTION: The Document Object Model (DOM) is the data representation of the objects that
comprise the structure and content of a document on the web. In this guide, we'll
briefly introduce the DOM. We'll look at how the DOM represents an HTML or XML
document in memory and how you use APIs to create web content and applications.
The Document Object Model (DOM) is a programming interface for HTML and XML
documents. It represents the page so that programs can change the document
structure, style, and content. The DOM represents the document as nodes and
objects. That way, programming languages can connect to the page.
A Web page is a document. This document can be either displayed in the browser
window or as the HTML source. But it is the same document in both cases. The
Document Object Model (DOM) represents that same 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.
The W3C DOM and WHATWG DOM standards are implemented in most modern
browsers. Many browsers extend the standard, so care must be exercised when using
them on the web where documents may be accessed by various browsers with
different DOMs [1].
IV. CONTENTS:
Lesson Coverage:
1. DOM Intro
2. DOM Methods
3. DOM Document
4. DOM Elements
5. DOM HTML
6. DOM CSS
7. DOM Animations
8. DOM Events
9. DOM Event Listener
DOM Intro
When a web page is loaded, the browser creates a Document Object Model of the page. The HTML DOM model is
constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
"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 HTML DOM is a standard object model and programming interface for HTML. It defines:
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements [2].
DOM 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.
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).
Example
The following example changes the content (the innerHTML) of the <p> element with id="demo":
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
The most common way to access an HTML element is to use the id of the element. In the example above
the getElementById method used id="demo" to find the element.
• 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>.
Example
This example demonstrates the change in a <p> tag content upon clicking a button:
<html>
<body>
<p id="demo"> Hi everyone! </p>
<button onclick = “changeText()”> Change </button>
<script>
function changeText(){
document.getElementById("demo").innerHTML = "Hello World!";
}
</script>
</body>
</html>
• The innerText property sets or returns the text content of the specified node, and all its descendants.
• If you set the innerText property, any child nodes are removed and replaced by a single Text node containing
the specified string.
Note: This property is similar to the textContent property, however there are some differences:
• textContent returns the text content of all elements, while innerText returns the content of all elements,
except for <script> and <style> elements.
• innerText will not return the text of elements that are hidden with CSS (textContent will).
Tip: To set or return the HTML content of an element, use the innerHTML property.
Example
This example demonstrates some of the differences between innerText, innerHTML and textContent:
<p id="demo">
This element has extra spacing and contains <span> a span element </span>.
</p>
<script>
function getInnerText() {
alert(document.getElementById("demo").innerText)
}
function getHTML() {
alert(document.getElementById("demo").innerHTML)
}
function getTextContent() {
alert(document.getElementById("demo").textContent)
}
</script>
Get the content of the <p> element above with the specified properties:
innerText returns: "This element has extra spacing and contains a span element."
innerHTML returns: " This element has extra spacing and contains <span>a span element</span>."
textContent returns: " This element has extra spacing and contains a span element."
The innerText property returns just the text, without spacing and inner element tags.
The innerHTML property returns the text, including all spacing and inner element tags.
The textContent property returns the text with spacing, but without inner element tags.
• The value property sets or returns the value of the value attribute of a text field.
• The value property contains the default value OR the value a user types in (or a value set by a script) [3].
Example 1
Example 2
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php" onsubmit="return myFunction()">
Name (max 10 characters): <input type="text" id="fname" size="20"
name="fname"><br>
<script>
function myFunction() {
let at = document.getElementById("email").value.indexOf("@");
let age = document.getElementById("age").value;
let fname = document.getElementById("fname").value;
let submitOK = "true";
if (submitOK == "false") {
return false;
}
}
</script>
</body>
</html>
DOM Document
The HTML DOM document object is the owner of all other objects in your web page.
If you want to access any element in an HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate HTML.
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and properties. These are still valid
in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were added [4].
DOM Elements
This lesson teaches you how to find and access HTML elements in an HTML page.
To do so, you have to find the elements first. There are several ways to do this:
The easiest way to find an HTML element in the DOM, is by using the element id.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let myElement = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"The text from the intro paragraph is " + myElement.innerHTML;
</script>
</body>
</html>
If the element is found, the method will return the element as an object (in myElement).
<!DOCTYPE html>
<html>
<body>
<p>Hello World!</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
<p id="demo"></p>
<script>
let x = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
'The text in first paragraph (index 0) is: ' + x[0].innerHTML;
</script>
</body>
</html>
This example finds the element with id="main", and then finds all <p> elements inside "main":
<!DOCTYPE html>
<html>
<body>
<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>
</div>
<p id="demo"></p>
<script>
let x = document.getElementById("main");
let y = x.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) inside "main" is: ' + y[0].innerHTML;
</script>
</body>
</html>
If you want to find all HTML elements with the same class name, use getElementsByClassName().
This example returns a list of all elements with class="intro".
<!DOCTYPE html>
<html>
<body>
<p>Hello World!</p>
<p id="demo"></p>
<script>
let x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
Finding elements by class name does not work in Internet Explorer 8 and earlier versions.
If you want to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values
of attributes, etc), use the querySelectorAll() method.
<!DOCTYPE html>
<html>
<body>
<p>Hello World!</p>
<p id="demo"></p>
<script>
let x = document.querySelectorAll("p.intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>
</body>
</html>
The querySelectorAll() method does not work in Internet Explorer 8 and earlier versions.
This example finds the form element with id="frm1", in the forms collection, and displays all element values [5]:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
let x = document.forms["frm1"];
let text = "";
let i;
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
DOM HTML
The HTML DOM allows JavaScript to change the content of HTML elements.
In JavaScript, document.write() can be used to write directly to the HTML output stream:
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
Never use document.write() after the document is loaded. It will overwrite the document.
The easiest way to modify the content of an HTML element is by using the innerHTML property.
<!DOCTYPE html>
<html>
body>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
Example explained:
<!DOCTYPE html>
<html>
<body>
h1 id="id01">Old Heading</h1>
<script>
let element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>
</body>
</html>
Example explained:
This example changes the value of the src attribute of an <img> element:
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("image").src = "landscape.jpg";
script>
<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>
</body>
</html>
Example explained:
DOM CSS
The HTML DOM allows JavaScript to change the style of HTML elements.
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontFamily = "Arial";
document.getElementById("p2").style.fontSize = "larger";
</script>
Using Events
The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
• An element is clicked on
• The page has loaded
• Input fields are changed
This example changes the style of the HTML element with id="id1", when the user clicks a button [7]:
Example 1
<!DOCTYPE html>
<html>
<body>
Example 2
<!DOCTYPE html>
<html>
<body>
<p id="p1">
This is a text.
This is a text.
This is a text.
This is a text.
</p>
</body>
</html>
DOM Animations
To demonstrate how to create HTML animations with JavaScript, we will use a simple web page:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
<div id ="container">
<div id ="animate">My animation will go here</div>
</div>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
<!Doctype html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
<body>
<div id="container">
<div id="animate"></div>
</div>
<body>
</html>
Animation Code
The changes are called by a timer. When the timer interval is small, the animation looks continuous [8].
function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<div id ="container">
<div id ="animate"></div>
<div>
<script>
let id = null;
function myMove() {
let elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>
</body>
</html>
DOM Events
Reacting to 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
In this example, the content of the <h1> element is changed when a user clicks on it:
<!DOCTYPE html>
<html>
body>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>
In the example above, a function named displayDate will be executed when the button is clicked.
The HTML DOM allows you to assign events to HTML elements using JavaScript:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick = displayDate;
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn".
The function will be executed when the button is clicked.
The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the proper version
of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
<!DOCTYPE html>
<html>
<body onload="checkCookies()">
<p id="demo"></p>
<script>
function checkCookies() {
let text = "";
if (navigator.cookieEnabled == true) {
text = "Cookies are enabled.";
} else {
text = "Cookies are not enabled.";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
The onchange event is often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the
content of an input field.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
let x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
<p>When you leave the input field, a function is triggered which transforms the input text to upper
case.</p>
</body>
</html>
The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of,
an HTML element:
<!DOCTYPE html>
<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}
function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
script>
</body>
</html>
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is
clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is
triggered, finally, when the mouse-click is completed, the onclick event is triggered [9].
<!DOCTYPE html>
<html>
<body>
<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<p id="demo"></p>
<script>
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
The addEventListener() method attaches an event handler to an element without overwriting existing event
handlers.
You can add many event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener() method makes it easier to control how the event reacts to bubbling.
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
The first parameter is the type of the event (like "click" or "mousedown" or any other HTML DOM Event.)
The second parameter is the function we want to call when the event occurs.
The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter
is optional.
Note that you don't use the "on" prefix for the event; use "click" instead of "onclick".
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
alert("Hello World!");
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to execute a function when a user clicks on a
button.</p>
<script>
document.getElementById("myBtn").addEventListener("click", myFunction);
function myFunction() {
alert ("Hello World!");
}
</script>
</body>
</html>
The addEventListener() method allows you to add many events to the same element, without overwriting existing
events:
<!DOCTYPE html>
<html>
body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to add two click events to the same
button.</p>
<script>
let x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);
function myFunction() {
alert ("Hello World!");
}
function someOtherFunction() {
alert ("This function was also executed!");
}
<script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to add many events on the same button.</p>
<p id="demo"></p>
<script>
let x = document.getElementById("myBtn");
x.addEventListener("mouseover", myFunction);
x.addEventListener("click", mySecondFunction);
x.addEventListener("mouseout", myThirdFunction);
function myFunction() {
document.getElementById("demo").innerHTML += "Moused over!<br>";
}
function mySecondFunction() {
document.getElementById("demo").innerHTML += "Clicked!<br>";
}
function myThirdFunction() {
document.getElementById("demo").innerHTML += "Moused out!<br>";
}
</script>
</body>
</html>
The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements,
the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.
Add an event listener that fires when a user resizes the window:
<!DOCTYPE html>
<html>
body>
<h2>JavaScript addEventListener()</h2>
<p>Try resizing this browser window to trigger the "resize" event handler.</p>
<p id="demo"></p>
<script>
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = Math.random();
});
</script>
</body>
</html>
Passing Parameters
When passing parameter values, use an "anonymous function" that calls the specified function with the parameters:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example demonstrates how to pass parameter values when using the addEventListener()
method.</p>
<p id="demo"></p>
<script>
let p1 = 5;
let p2 = 7;
document.getElementById("myBtn").addEventListener("click", function() {
myFunction(p1, p2);
});
function myFunction(a, b) {
let result = a * b;
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
There are two ways of event propagation in the HTML DOM, bubbling and capturing.
Event propagation is a way of defining the element order when an event occurs. If you have a <p> element inside a
<div> element, and the user clicks on the <p> element, which element's "click" event should be handled first?
In bubbling the inner most element's event is handled first and then the outer: the <p> element's click event is
handled first, then the <div> element's click event.
In capturing the outer most element's event is handled first and then the inner: the <div> element's click event will
be handled first, then the <p> element's click event.
With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter:
The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the
capturing propagation.
<!DOCTYPE html>
<html>
<head>
<style>
#myDiv1, #myDiv2 {
background-color: coral;
padding: 50px;
}
#myP1, #myP2 {
background-color: white;
font-size: 20px;
border: 1px solid;
padding: 20px;
}
</style>
<h2>JavaScript addEventListener()</h2>
<div id="myDiv1">
<h2>Bubbling:</h2>
<p id="myP1">Click me!</p>
</div><br>
<div id="myDiv2">
<h2>Capturing:</h2>
<p id="myP2">Click me!</p>
</div>
<script>
document.getElementById("myP1").addEventListener("click", function() {
alert("You clicked the white element!");
}, false);
document.getElementById("myDiv1").addEventListener("click", function() {
alert("You clicked the orange element!");
}, false);
document.getElementById("myP2").addEventListener("click", function() {
alert("You clicked the white element!");
}, true);
document.getElementById("myDiv2").addEventListener("click", function() {
alert("You clicked the orange element!");
}, true);
</script>
</body>
</html>
The removeEventListener() method removes event handlers that have been attached with the addEventListener()
method [10]:
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
background-color: coral;
border: 1px solid;
padding: 50px;
color: white;
font-size: 20px;
}
</style>
</head>
<body>
<h2>JavaScript removeEventListener()</h2>
<div id="myDIV">
<p>This div element has an onmousemove event handler that displays a random number
every time you move your mouse inside this orange field.</p>
<p id="demo"></p>
<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = Math.random();
}
function removeHandler() {
document.getElementById("myDIV").removeEventListener("mousemove",
myFunction);
}
</script>
</body>
</html>
V. REFERENCES: [1] MDN Web Docs, “Introduction to the DOM”, [Online]. Available:
https://developer.mozilla.org/en-
DISCLAIMER
Every reasonable effort is made to ensure the accuracy of the information used in the creation of this
reference material, without prejudice to the existing copyrights of the authors. As an off-shoot of the innumerable
difficulties encountered during these trying times, the authors endeavored to ensure proper attribution of the
esteemed original works, by way of footnotes or bibliography, to their best abilities and based on available resources,
despite the limited access and mobility due to quarantine restrictions imposed by the duly constituted authorities.
COPYRIGHT NOTICE
Materials contained in the learning packets have been copied and conveyed to you by or on behalf of
Pamantasan ng Cabuyao pursuant to Section IV - The Copyright Act (RA) 8293 of the Intellectual Property Code of
the Philippines.
You are not allowed by the Pamantasan ng Cabuyao to reproduce or convey these materials. The content may
contain works which are protected by copyright under RA 8293. You may be liable to copyright infringement for any
copying and/ or distribution of the content and the copyright owners have the right to take legal action against such
infringement.