Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 DOM Dr. Reda Salama

2 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

3 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

4 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

5 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

6 The DOM object hierarchy 6

7 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 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

9 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

10 DOM Tree: Example JS Page Delhi Mumbai Chennai Kolkata 10

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

23 Anchor Object – href, target function changeLink() { document.getElementById('myAnchor').innerHTML="Visit KAU"; document.getElementById('myAnchor').href="http://www.kau.edu.sa"; 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 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

32 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

33 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

34 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

35 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

36 DOM Demonstration Example.. 36

37 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

38 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 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 http://www.w3.org/TR/DOM-Level-3-Core/. The DOM Level 2 HTML Specification, available at http://www.w3.org/TR/DOM-Level-2-HTML/, 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 40 W3C Document Object Model. Summary of the DOM Objects and Collections

41 41 Summary of the DOM Objects and Collections

42 42 Summary of the DOM Objects and Collections

43 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

44 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

45 Tutorial & Refereces JavaScript and HTML DOM Reference http://www.w3schools.com/jsref/ http://www.w3schools.com/jsref/dom_obj_document.asp http://www.w3schools.com/jsref/tryit.asp?filename=tryj sref_form_elements 45


Download ppt "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."

Similar presentations


Ads by Google