DOM Dr. Reda Salama. Back to the HTML DOM Once we get a response back from the server, we probably want to update our HTML page The HTML page itself is.

Slides:



Advertisements
Similar presentations
The Document Object Model
Advertisements

The jQuery library. What is jQuery ? A javascript lightweight library Is very easy to use Is powerful Is cross-browser compatible Downloadable from jQuery.com,
JavaScript Part 6. Calling JavaScript functions on an event JavaScript doesn’t have a main function like other programming languages but we can imitate.
Lesson 12- Unit L Programming Web Pages with JavaScript.
The Web Warrior Guide to Web Design Technologies
Document Object Model. Lecture 18 The Document Object Model (DOM) is not a programming language It is an object-oriented model of web documents Each.
Tutorial 16 Working with Dynamic Content and Styles.
20-Jun-15 JavaScript and HTML Simple Event Handling.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
JavaScript, Third Edition
14-Jul-15 Ajax. The hype Ajax (sometimes capitalized as AJAX) stands for Asynchronous JavaScript And XML Ajax is a technique for creating “better, faster,
DHTML. What is DHTML?  DHTML is the combination of several built-in browser features in fourth generation browsers that enable a web page to be more.
4.1 JavaScript Introduction
HTML DOM.  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree- structure.
JS: Document Object Model (DOM)
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 JavaScript and HTML Documents.
JavaScript & DOM Client-side scripting. JavaScript JavaScript is a tool to automate client side (which is implemented using HTML so far) JavaSript syntax.
UFCEWT-20-3 Advanced Topics in Web Development Lecture 4 : JavaScript, Browsers & the HTML DOM-API.
DOM and JavaScript Aryo Pinandito.
Lecture 11 – DOM Scripting SFDV3011 – Advanced Web Development Reference: 1.
D2L Notes Be sure to submit your link in the dropbox provided on D2L You can just upload an empty text file if a file upload is required Do not use D2L.
Working with the XML Document Object Model ©NIITeXtensible Markup Language/Lesson 7/Slide 1 of 44 Objectives In this lesson, you will learn to: *Identify.
JavaScript – The DOM JavaScript is object based The browser is object based – We can access the browser's objects in the same way we did JavaScript's Two.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
5.2 DOM (Document Object Model). 2 Motto: To write it, it took three months; to conceive it three minutes; to collect the data in it — all my life. —F.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Javascript II DOM & JSON. In an effort to create increasingly interactive experiences on the web, programmers wanted access to the functionality of browsers.
 2008 Pearson Education, Inc. All rights reserved Introduction to XHTML.
JavaScript IV ECT 270 Robin Burke. Outline DOM JS document model review W3C DOM.
Chapter 5: Windows and Frames
XP Tutorial 16 New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with Dynamic Content and Styles Creating a Dynamic Table of Contents.
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.
1 Dr Alexiei Dingli XML Technologies SAX and DOM.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.2 Revised by Dr. T. Tran for CSI3140.
Introduction to the Document Object Model Eugenia Fernandez IUPUI.
JavaScript, Fourth Edition Chapter 4 Manipulating the Browser Object Model.
1 Javascript DOM Peter Atkinson. 2 Objectives Understand the nature and structure of the DOM Add and remove content from the page Access and change element.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
Review of the DOM Node properties and methods Some ways of accessing nodes Appending, copying and removing nodes Event handling – Inline – Scripting –
Document Object Model. Back to the DOM… Javascript and the DOM  Originally, the Document Object Model (DOM) and Javascript were tightly bound  Each.
CO1552 – Web Application Development Further JavaScript: Part 1: The Document Object Model Part 2: Functions and Events.
Rich Internet Applications 3. Client JavaScript. Document Object Model (DOM) The DOM, is an interface that allows scripts or programs to access and manipulate.
DOM (Document Object Model) - Parsing and Reading HTML and XML -
Dr. Ahmet Cengizhan Dirican BIL 374 Internet Technologies 5. JavaScript and HTML Documents.
School of Computing and Information Systems CS 371 Web Application Programming JavaScript - DOM Modifying the Page from within.
Advanced DOM Builds on last presentation on DOM Allows you to dynamically create elements and position them on a page DOM methods/properties are W3C standard.
Host Objects: Browsers and the DOM
Computer Information System Information System California State University Los Angeles Jongwook Woo CIS 461 Web Development I HTML DOM part I Jongwook.
Document Object Model.  The XML DOM (Document Object Model) defines a standard way for accessing and manipulating XML documents.  The DOM presents an.
Create Element, Remove Child. The Document Tree Document Element Root Element Element Element Element Element Text: HelloWorld Attribute “href”
JS: Document Object Model (DOM) DOM stands for Document Object Model, and allows programmers generic access to: DOM stands for Document Object Model, and.
Department of Computer Science, Florida State University CGS 3066: Web Programming and Design Spring
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
XML DOM Week 11 Web site:
Introduction to JavaScript DOM Instructor: Sergey Goldman.
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Chapter 5 Host Objects: Browsers.
XP Tutorial 10 New Perspectives on JavaScript, Comprehensive 1 Working with Dynamic Content and Styles Creating a Dynamic Table of Contents.
THE DOM.
DHTML.
JavaScript and HTML Simple Event Handling 11-May-18.
Scripting the DOM MIS 3502, Fall 2016 Jeremy Shafer Department of MIS
Applied Online Programming
CS 371 Web Application Programming
Introduction to the Document Object Model
Document Object Model (DOM): Objects and Collections
Week 11 Web site: XML DOM Week 11 Web site:
CHAPTER 7 JavaScripts & HTML Documents
Presentation transcript:

DOM Dr. Reda Salama

Back to the HTML DOM Once we get a response back from the server, we probably want to update our HTML page The HTML page itself is document You can get information from the HTML page var price = document.getElementById("price").value; var allImages = document.getElementsByTagName("img"); var firstImg = document.getElementsByTagName("img")[0]; We can use the DOM to change the HTML 2

innerHTML innerHTML is a non-W3C DOM property that gets or sets the text between start and end tags of an HTML element When the innerHTML property is set, the given string completely replaces the existing content of the object If the string contains HTML tags, the string is parsed and formatted as it is placed into the document Syntax: var markup = element.innerHTML; element.innerHTML = markup ; Example: document.getElementById( someId ).innerHTML = response ; innerHTML is nonstandard 3

and again... and... are containers Like for paragraph, there is a blank line before and after a Like for italics, does not affect spacing or flow The primary use of these tags is to hold an id attribute With an id, we can manipulate page content // Find thing to be replaced var mainDiv = document.getElementById("main-page"); var orderForm = document.getElementById("target"); // Create replacement var paragraph = document.createElement("p"); var text = document.createTextNode("Here is the new text."); paragraph.appendChild(text); // Do the replacement mainDiv.replaceChild(paragraph, target); 4

DOM (Document Object Model) in details The Document Object Model gives you access to all the elements on a web page. Using any programming language, you can create, modify and remove elements in the page dynamically. The DOM is separated into 3 different parts / levels: Core DOM - standard model for any structured document XML DOM - standard model for XML documents HTML DOM - standard model for HTML documents With the DOM, XHTML elements can be treated as objects, and many attributes of XHTML elements can be treated as properties of those objects. Then, objects can be scripted (through their id attributes) with JavaScript to achieve dynamic effects. Warning: - The DOM is accessible only when the whole document has been loaded.That’s the reason the DOM access code is executed only after the load event has been fired. 5

The DOM object hierarchy 6

DOM Collections The Document Object Collections are groups of related objects on a page. They are array-valued properties,. They are the properties that give you access to certain especial elements of the document:  anchors[ ]  applets[ ]  forms[ ]  images[ ]  links[ ] To find the number of elements in the collection, use the collection’s length property. document.anchors.length returns number of Their elements are in the same order as in the document source code. document.forms[0] refers to the first tag in the document. document.images[10] refers to the tenth tag in the document. 7

8 DOM Collections (Cont.) Access items in a collection via square brackets item method of a DOM collection Access specific elements in a collection, taking an index as an argument namedItem method takes a name as a parameter and finds the element in the collection, if any, whose id attribute or name attribute matches it href property of a DOM link node Refers to the link’s href attribute Collections allow easy access to all elements of a single type in a page Useful for gathering elements into one place and for applying changes across an entire page Example of Collection of type link

Naming Document Objects In the legacy DOM, with the name attribute, you can assign names to important document elements and to refer to those elements by name: Assuming that the is the first one in the document: document.forms[0]// refer to the form by position document.f1// refer to the form by name document.forms[“f1”]// refer to the form as array index Setting the name attribute of a,, or (but not of and >) also makes the corresponding Form, Image, or Applet object accessible as a named property of the document object itself. Thus, you can also refer to the form as: document.f1 You have a form that looks like this: /* you can refer to the text input field element as : */ document.shipping.zipcode 9

DOM Tree: Example JS Page Delhi Mumbai Chennai Kolkata 10

HTML DOM Nodes HTML documents have a hierarchical structure of nested tags that is represented in the DOM as a tree of objects. The tree representation of an HTML document contains nodes representing HTML tags or elements, e.g and The HTML DOM defines the objects and properties of all HTML elements, and the methods to access them. Everything in an HTML document is a node. The entire document is a document node Every HTML tag is an element node The text in the HTML elements are text nodes Every HTML attribute is an attribute node Comments are comment nodes

HTML DOM Node Tree (Document Tree) All the nodes in a node tree have relationships to each other. The tree structure is called a node-tree. Node:- Parents, Children, and Siblings 12

DOM Element Attributes nodeName nodeValue nodeType parentNode childNodes firstChild lastChild previousSibling nextSibling attributes ownerDocument 1 = an HTML element 2 = an element attribute 3 = text 8 = an HTML comment 9 = a document 10 = a document type definition DOM AttributesNode Types (12) 13

HTML DOM Node Tree (Document Tree) DOM I am in DOM world Hello DOM! In a node tree, the top node is called the root Every node, except the root, has exactly one parent node A node can have any number of children A leaf is a node with no children Siblings are nodes with the same parent The node has no parent node; the root node The parent node of the and nodes is the node The parent node of the "Hello world!" text node is the node 14

HTML DOM Node Tree (Document Tree) Most element nodes have child nodes: The node has two child nodes; and The node has one child node; the node The node also has one child node; the text node "DOM Tutorial“ The and nodes are siblings, and both child nodes of DOM I am in DOM world Hello DOM! 15

HTML DOM Properties and Methods Properties are often referred to as atributes that describes the node (i.e. nodename is "p"). Methods are often referred to as something that is done (i.e. delete "p"). DOM Properties (attributes) These are some typical DOM properties: x.nodeName - the name of x x.nodeValue - the value of x x.parentNode - the parent node of x x.childNodes - the child nodes of x x.attributes - the attributes nodes of x Note: In the list above, x is a node object. 16

Finding DOM Elements & DOM Methods You can access a node in three ways: 1. By using the getElementById() method 2. By using the getElementsByTagName() method 3. By navigating the node tree, using the node relationships ) x.getElementByID(id) - get the element with a specified id x.getElementsByTagName(name) - get all elements with a specified tag name document.getElementsByName(name) returns a collection of objects with the specified NAME Note: In the list above, x is a node object. 17

Examples: Finding DOM Elements 1- return the text from a Hello DOM! txt=document.getElementById("intro"). childNodes[0].nodeValue Display:- “Hello DOM!” document - the current HTML document getElementsById("intro") - the element with the id "intro" childNodes[0] - the first child of the element (the text node) nodeValue - the value of the node (the text itself) 2- returns first paragraph inside third div in document. document.getElementsByTagName('div')[2].getElementsByTagN ame('p')[0]; 3- returns fourth link inside element with the ID ‘nav‘ document.getElementById(‘nav).getElementsByTagName('a')[3]; 18

getElementsByTagName() W3Schools example The DOM is very useful This example demonstrates how to use the getElementsByTagName method x=document.getElementById("main").getElementsByTagName("p "); document.write("First paragraph inside the main div: " + x[0].childNodes[0].nodeValue); 19

getElementsByTagName() example returns a nodeList of all elements that are descendants of the element with id="main": document.getElementById('main').getElementsByTagName("p"); The nodeList object represents a node and its child nodes as a node tree. The nodeList object represents a node and its child nodes as a node tree. Property of Nodelist: Property of Nodelist: length:Returns an unsigned long integer indicating the number of nodes in the NodeList. length:Returns an unsigned long integer indicating the number of nodes in the NodeList. Method of Nodelist: Method of Nodelist: item(index):This method takes an index as its argument and returns the node at that index position. item(index):This method takes an index as its argument and returns the node at that index position. x=document.getElementsByTagName("p"); for(i=0;i "); } 20

Navigating Node Relationships The three properties parentNode, firstChild, and lastChild follow the document structure and allow short-distance travel in the document. W3Schools example The DOM is very useful This example demonstrates node Relationships 21

Navigating Node Relationships the is the first child node (firstChild) of the element, and the element is the last child node (lastChild) of the element. Furthermore, the is the parent (parentNode). The firstChild property can be used to access the text of an element. x=document.getElementById("intro"); var text=x.firstChild.nodeValue; 22

Anchor Object – href, target function changeLink() { document.getElementById('myAnchor').innerHTML="Visit KAU"; document.getElementById('myAnchor').href=" document.getElementById('myAnchor').target="_blank"; } Visit Microsoft In this example we change the text and the URL of a hyperlink. We also change the target attribute. The target attribute is by default set to "_self", which means that the link will open in the same window. By setting the target attribute to "_blank", the link will open in a new window. 23

Image Object – resize, change src function changeSize() { document.getElementById(“ccsf").height="250"; document.getElementById(“ccsf").width="300"; } function changeSrc() { document.getElementById(“ccsf").src=“colan.gif"; } 24

Table Object – update cells function changeContent() { var x=document.getElementById('myTable').rows[0].cells; x[0].innerHTML="NEW CONTENT"; x[1].innerHTML="NEW TOO"; } Row1 cell1 Row1 cell2 Row2 cell1 Row2 cell2 Row3 cell1 Row3 cell2 25

Table Object – display cell function dsptxt(id) { alert(document.getElementById(“mytable”).innerHTML); } Cell 1 data Cell 2 data Cell 3 data Cell 4 data Cell 5 data Cell 6 data Cell 7 data Cell 8 data 26

Navigating Node Relationships The three properties parentNode, firstChild, and lastChild follow the document structure and allow short-distance travel in the document. W3Schools example The DOM is very useful This example demonstrates node Relationships This was the last 27

Root Nodes There are two special document properties that allow access to the tags: document.documentElement document.body The first property returns the root node of the document and exists in all XML and HTML documents. It efers to the tag that serves as the root element of the document. The second property is a special addition for HTML pages, and gives direct access to the tag. The body property of the HTML Document object is a convenient special-case property:document.getElementsByTagName(“body”)[0] This expression calls the Document object’s getElementsByTagName() method and selects the first element of the returned array. 28

Node Property Everything in a document can be considered a node, including the document itself. Properties Of Node (Attributes): nodeName : Returns name of element. nodeValue : Returns value of element. nodeType : Returns type of node (text, element, etc) parentNode : Contains the parent node (for nodes that can have parents). childNodes : Contains a node list containing the children (for nodes that can have children). firstChild : Contains the first child of this node. 29

Node Property (Cont.) lastChild: Returns the last child node. previousSibling: Contains the left sibling of this node nextSibling: Contains the next sibling of this node in the parent's child list. attributes: Contains the list of attributes for this node. getAttributes(); setAttributes(); 30

Node Property (Cont.) insertBefore(newchild, refchild): Inserts a child node to the left of the specified node or at the end of the list. replaceChild(newchild, oldchild): Replaces the specified old child node with the supplied new child node in the set of children of this node, and returns the old child node. removeChild(oldchild): Removes the specified child node from the list of children and returns it. appendChild(newchild):Appends newChild as the last child of this nodeappendChild(newchild):Appends newChild as the last child of this node createElement(tagName) :Creates an new element with the specified tagName createTextNode(text) : Creates a text node, containing the specified text. createAttribute(attributeName) : Creates an attribute node with the specified attribute name 31

Examples: Node maniplulations Append a new child node: Add a new “paragraph” as the last Child of the body element. var paragraph= document.createElement("p"); var text = document.createTextNode("Here is the new paragraph."); paragraph.appendChild(text); document.body.appendChild(paragraph); What if we execute the following 2 lines instead of the last line above? Paragraph is appended to div section var mainDiv = document.getElementById("main"); mainDiv.appendChild(paragraph); 32

Examples: Node maniplulations Replace a child node with a new node: first child from body element is the paragraph “ W3Schools example” will be replaced with the new node var paragraph= document.createElement("p"); var text = document.createTextNode("Here is the new paragraph."); paragraph.appendChild(text); target = document.body.firstChild document.body.replaceChild(paragraph, target); What if we want target = document.body.childNodes[1] document.body.replaceChild(paragraph, target);t to replace the Div section? 33

Examples: Node maniplulations Insert new child node after a node: Insert a new paragraph node before the div section. var paragraph= document.createElement("p"); var text = document.createTextNode("Here is the new paragraph."); paragraph.appendChild(text); target = document.body.childNodes[1] document.body.insertBefore(paragraph, target); Insert new child node after a node: Insert a new paragraph node at the end of body. document.body.insertBefore(paragraph, null); 34

Examples: Node maniplulations Delete a child node : third “paragraph” from the body element. This means the paragraph. with sentence “This was the last” x=document.body; y=x.childNodes[2]; z=x.removeChild(y); 35

DOM Demonstration Example.. 36

DOM Demonstration Example (Cont.) Each document element tag has an id H1 = bigheading, H3 = smallheading, p = para1, p=para2, a= link, p=para3, ul = list, li = item1, li = item2, li = item3, div = nav Table contains id, text fields and corresponding method: id = gbi, value = Get By id, method = byId() id = ins, value = Insert Before, method = insert() id= append, value = Append Child, method = appendNode() id = replace, value = Replace Current, method = replaceCurrent() Last 2 rows of the table don’t have id and text fields 37

DOM Demonstration Example (Cont.) Let’s now demonstrate and study the whole script in detail. Now you are able to take home work with you Add a new method that can traverse from any given node even the Html node of body. Modify the script to remove any node at the document but take care not to delete the html, head, body and script. Modify the script to get the patent of any node Modify the script to create new nodes with other tags than P. Modify the script with any functionality you may find. 38

39 Summary of the DOM Objects and Collections The objects and collections in the W3C DOM give you flexibility in manipulating the elements of a web page. The W3C DOM allows you to access every element in an XHTML document. Each element in a document is represented by a separate object. For a reference on the W3C Document Object Model, see the DOM Level 3 recommendation from the W3C at The DOM Level 2 HTML Specification, available at describes additional DOM functionality specific to HTML, such as objects for various types of XHTML elements. Not all web browsers implement all features included in the DOM specification.

40 W3C Document Object Model. Summary of the DOM Objects and Collections

41 Summary of the DOM Objects and Collections

42 Summary of the DOM Objects and Collections

Adding and removing event handlers You can add event handlers to HTML elements You can also add handlers programmatically, from a JavaScript function: var act = document.getElementById("act"); act.onclick = takeAction; var images = document.getElementsByTagName("img"); for (var i = 0; i < images.length; i++) { images[i].onclick = expandImage; } Inside expandImage, the particular image is in the variable this Remember: JavaScript is case sensitive, HTML isn't! You can programmatically remove event handlers act.onclick = null 43

Events Click Dblclick Mousedown Mouseup Mouseover Mousemove Mouseout  Keypress  Keydown  Keyup  Select  Change  Submit  Reset  Focus  Blur  Load  Unload  Abort  Error  Resize  Scroll Mouse Keyboard Frame/ObjectForm 44

Tutorial & Refereces JavaScript and HTML DOM Reference sref_form_elements 45