Lecture Web Technology and online services: Lesson 8 - Document object model (DOM) provide students with knowledge about: Introduction to DOM; DOM Methods; DOM Document; DOM Elements; DOM - Changing HTML; DOM - Changing CSS; DOM Animation;... Please refer to the detailed content of the lecture!
Trang 1Lecture 8: Document Object
Model (DOM)
Trang 2Document Object Model (DOM)
Trang 3Document Object Model (DOM)
3
Trang 4What is the DOM?
❖ The DOM is a W3C (World Wide Web Consortium)
standard.
❖ The DOM defines a standard for accessing documents:
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
Trang 5What is the HTML DOM?
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
how to get, change, add, or delete HTML
elements.
5
Trang 6The HTML DOM (Document Object Model)
a Document Object Model of the page.
of Objects:
Trang 7With the object model, JavaScript gets all the power it needs to create dynamic HTML
❖ JavaScript can change all the HTML elements in the
page
❖ JavaScript can change all the HTML attributes in the
page
❖ JavaScript can change all the CSS styles in the page
❖ JavaScript can remove existing HTML elements and
attributes
❖ JavaScript can add new HTML elements and attributes
❖ JavaScript can react to all existing HTML events in the
page
❖ JavaScript can create new HTML events in the page
7
Trang 9Document Object Model (DOM)
9
Trang 10HTML DOM Methods and HTML DOM
properties
(on HTML Elements)
Elements) that you can set or change
Trang 11The DOM Programming Interface
(and with other programming languages)
as objects.
methods of each object
❖ A property is a value that you can get or set (like
changing the content of an HTML element)
deleting an HTML element)
11
Trang 12❖ In the example belows, getElementById is a method,
while innerHTML is a property.
❖ The getElementById Method: the most common way to
access an HTML element is to use the id of the element.
❖ The innerHTML Property: The easiest way to get the
content of an element is by using the innerHTML property.
Trang 13Document Object Model (DOM)
13
Trang 14JavaScript HTML DOM Document
all other objects in your web page
page, you always start with accessing the
document object
Trang 17Adding and Deleting Elements
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
stream
Trang 18Finding HTML Objects
collections, and properties These are still valid in HTML5.
were added.
18
document.anchors Returns all <a> elements that have a name
document.body Returns the <body> element 1
document.cookie Returns the document's cookie 1
document.doctype Returns the document's doctype 3
document.documentEleme
nt
Returns the <html> element 3
document.documentMode Returns the mode used by the browser 3
Trang 19Document Object Model (DOM)
19
Trang 20JavaScript HTML DOM Elements
HTML elements
are several 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
Trang 21<p id = "intro" > Hello World! </p>
<p> This example demonstrates the <b> getElementsById </b> method </p>
<p id = "demo" ></p>
<script>
var myElement = document.getElementById( "intro" );
document.getElementById( "demo" ).innerHTML = "The text from the intro paragraph is " + myElement.innerHTML;
</script>
</body>
</html>
Trang 22Finding HTML Elements by Tag Name
❖ This example finds all <p> elements:
document.getElementById( "demo" ).innerHTML =
'The text in first paragraph (index 0) is: ' + x[ 0 ].innerHTML;
</script>
</body>
</html>
Trang 23Finding HTML Elements by Class Name
same class name, use getElementsByClassName()
with class="intro"
23
var x = document.getElementsByClassName("intro");
Trang 24Finding HTML Elements by CSS Selectors
specified CSS selector (id, class names, types,
attributes, values of attributes, etc), use
the querySelectorAll() method
❖ This example returns a list of all <p> elements
with class="intro"
var x = document.querySelectorAll("p.intro");
Trang 25Finding HTML Elements by HTML Object Collections
25
<html>
<body>
<h2> Finding HTML Elements Using document.forms </h2>
<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>
Trang 26Finding HTML Elements by HTML Object Collections
<html>
<body>
<h2> Finding HTML Elements Using document.forms </h2>
<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>
Trang 27Document Object Model (DOM)
27
Trang 29Changing the HTML Output Stream
write directly to the HTML output stream:
Trang 30Changing 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
Trang 31var element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>
</body>
</html>
Trang 32Changing the Value of an Attribute
syntax:
attribute of an <img> element:
document.getElementById(id).attribute = new value
Trang 33Changing the Value of an Attribute
syntax:
attribute of an <img> element:
Trang 34Document Object Model (DOM)
Trang 35Changing CSS
❖ The HTML DOM allows JavaScript to change the style of
HTML elements.
❖ To change the style of an HTML element, use this syntax:
❖ The following example changes the style of a <p> element:
Trang 36Changing CSS
❖ The HTML DOM allows JavaScript to change the style of
HTML elements.
❖ To change the style of an HTML element, use this syntax:
❖ The following example changes the style of a <p> element:
document.getElementById(id).style.property = new style
Trang 37▪ The page has loaded
▪ Input fields are changed
37
Trang 38Using Events - Example
element with id="id1", when the user clicks a
<button type ="button"
Click Me!</button>
</body>
</html>
Trang 39Using Events – Example 2
<input type = "button" value = "Hide text"
onclick = "document.getElementById( 'p1' ).style.visibility = 'hidden' ">
<input type = "button" value = "Show text"
onclick = "document.getElementById( 'p1' ).style.visibility = 'visible' ">
</body>
</html>
Trang 40Document Object Model (DOM)
Trang 41JavaScript HTML DOM Animation
gradual changes in an element's style
interval is small, the animation looks continuous
Trang 42Example
Trang 45Document Object Model (DOM)
45
Trang 46JavaScript 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
❖ Examples of HTML events:
▪ When a user clicks the mouse
▪ When a web page has loaded
▪ When an image has been loaded
▪ When the mouse moves over an element
▪ When an input field is changed
▪ When an HTML form is submitted
▪ When a user strokes a key
onclick=JavaScript
Trang 47Reacting to Events
❖ In this example, the content of the <h1> element
is changed when a user clicks on it:
Trang 49HTML Event Attributes
❖ To assign events to HTML elements you can use event
attributes.
❖ In the example, a function named displayDate will be
executed when the button is clicked.
49
<html>
<body>
<p> Click the button to display the date </p>
<button onclick = "displayDate()"> The time is? </button>
Trang 50Assign Events Using the HTML DOM
JavaScript:
element with the id="myBtn".
<html>
<body>
<p> Click "Try it" to execute the displayDate() function </p>
<button id = "myBtn"> Try it </button>
Trang 51Assign Events Using the HTML DOM
JavaScript:
element with the id="myBtn".
51
<html>
<body>
<p> Click "Try it" to execute the displayDate() function </p>
<button id = "myBtn"> Try it </button>
Trang 52The onload and onunload Events
when the user enters or leaves the page
visitor's browser type and browser version, and load the proper version of the web page based on the information
deal with cookies
Trang 53The onload and onunload Events
Trang 54The onchange Event
❖ 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.
Enter your name: <input type = "text" id = "fname" onchange = "myFunction()" >
<p> When you leave the input field, a function is triggered which transforms the input text to upper case </p>
</body>
</html>
Trang 55The onchange Event
❖ 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.
Enter your name: <input type = "text" id = "fname" onchange = "myFunction()" >
<p> When you leave the input field, a function is triggered which transforms the input text to upper case </p>
</body>
</html>
Trang 56The onmouseover and onmouseout Events
❖ The onmouseover and onmouseout events can be used to
trigger a function when the user mouses over, or out of, an HTML element:
Trang 57The onmousedown, onmouseup and
onclick Events
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
57
Trang 58The onmousedown, onmouseup and
Trang 59Document Object Model (DOM)
59
Trang 60JavaScript 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.
❖ 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.
Trang 61JavaScript HTML DOM EventListener
❖ The first parameter is the type of the event (like
"click" or "mousedown" or any other HTML DOM Event.)
call when the event occurs
whether to use event bubbling or event capturing This parameter is optional
❖
61
element.addEventListener(event, function, useCapture);
Trang 62Add an Event Handler to an Element
<!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>
<script>
document.getElementById( "myBtn" ).addEventListener( "click" , function () {
alert( "Hello World!" );
});
</script>
</body>
</html>
Trang 63Add an Event Handler to an Element
❖ You can also refer to an external "named"
function:
63
element.addEventListener("click", myFunction);
function myFunction() { alert ("Hello World!");
}
element.addEventListener("click", function(){ alert("Hello World!");});
Trang 64Add Many Event Handlers to the Same
Element
many events to the same element, without
overwriting existing events:
element:
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
Trang 65Add an Event Handler to the window Object
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
user resizes the window:
65
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = sometext;
});
Trang 66Passing 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> Click the button to perform a calculation </p>
<button id = "myBtn" > Try it </button>
Trang 67Passing Parameters
❖ When passing parameter values, use an "anonymous
function" that calls the specified function with the parameters:
<p> Click the button to perform a calculation </p>
<button id = "myBtn" > Try it </button>
Trang 68Event Bubbling or Event Capturing?
❖ 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.