Document Object Model

You might also like

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

DOCUMENT OBJECT

MODEL
CS 109e
What is the DOM?
• DOM stands for Document Object Model?
• An API for HTML and XML
• Defines the logical structure of documents
• Defines the way a document is accessed
• Defines the way a document is manipulated
• Closely resembles the structure of the document it
models
The W3C DOM

The W3C DOM standard is separated into 3


different parts:
1.Core DOM
2.XML DOM
3.HTML DOM
What the DOM can do
• Create and build documents
• Navigate through the structure of documents
• Add, edit, delete elements of a document
• Add, edit, delete content of a document
What the DOM is for

• Provide a standard programming interface


that can be used for documents in a wide
variety of environments and applications
The HTML DOM

When a webpage is loaded, the browser


creates a document object model of the
page.
The HTML DOM is constructed as a tree of
objects
DOM Structure
<TABLE>
<ROWS> The DOM
<TR>
<TD>Donato, Michelle</TD> representation
<TD>Cabuyao</TD> of the example
</TR>
<TR> table
<TD>Alforja, Kent</TD>
<TD>Calamba</TD>
</TR>
</ROWS>
</TABLE>
The DOM representation of the example table

Donato, Alforja,
Cabuyao Kent Calamba
Michelle
Object Modeling
• Documents are modelled using objects.
• The model encompasses both structure and
behaviour of which it is composed.
• In the diagram (DOM representation of <table>),
the nodes do not represent a data structure but
objects – which have functions and identity.
Trees, Forest

• In the DOM, documents have logical


structure which is very much a tree-like
structure.
• The DOM may contain more than one tree
so it may be more like a forest
The HTML DOM Tree of Objects
With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
1. Change all the elements in the page
2. Change all the HTML attributes in the page
3. Change all the CSS styles in the page
4. Remove existing HTML elements and attributes
5. React to all existing HTML events in the page
6. Create new HTML events in the page
Trees, Forest
• Structural isomorphism: if any two Document Object
Model implementations are used to create a
representation of the same document, they will create
the same structure model, with precisely the same
objects and relationship
DOM Identifies
• The interfaces and objects used to
represent and manipulate a document.
• The semantics of these interfaces and
objects - including both behavior and
attributes.
• The relationships and collaborations among
these interfaces and objects.
SGML Versus XML

•SGML – represented by an abstract


data model (centered around the
data)
•XML – represented by an object
model (centered around the object)
What DOM is not!!
• The Document Object Model is not a binary
specification.
• The Document Object Model is not a way of
persisting objects to XML or HTML.
• The Document Object Model does not define
"the true inner semantics" of XML or HTML.
What the DOM is not!
• The Document Object Model is not a set of data
structures, it is an object model that specifies
interfaces.
• The Document Object Model is not a competitor to
the Component Object Model (COM).
The COM as Introduced by Microsoft
The DOM Programming Interface
In the DOM, all HTML elements are defined as objects.
1. The programming interface is the properties and
methods of each object.
2. A property is a value that you can GET or SET (e.g.
changing the content of an HTML element)
3. A method is an action you can do (like adding or
deleting an HTML element)
Changing 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>
 
Changing the content (the innerHTML) of the
<p> element with id="demo":
In the example, 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.
• In the example above the getElementById
method used id="demo" to find the
element.
The innerHTML Property
• The easiest way to get the content of an
element is by using the innerHTMLproperty.
• 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>.
Finding HTML Elements
Method Description
document.getElementById(id) Find an
element by
element id
document.getElementsByTagName(name) Find elements
by tag name
document.getElementsByClassName(name) Find elements
by class name
Finding HTML Elements by Tag Name

Example:
var x =
document.getElementsByTagName("p");

The above example finds all <p> elements:


Finding HTML Elements by Tag Name

Example:
var x = document.getElementsById("
main");
var x = x.getElementsByTagName("p");

The above example finds the element with id = “main”


and then finds all <p> elements inside “main”.
Finding HTML Elements by Class Name
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".

Example
var x = document.getElementsByClassName("intro");
Finding HTML Elements by CSS Selectors
If you want to find all HTML elements that matches a 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".

Example
var x = document.querySelectorAll("p.intro");
Finding HTML Elements by HTML Object
Collections
This example finds the form element with id="frm1", in the forms
collection, and displays all element values:

Example
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length; i++) {
    text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
The following HTML objects (and object collections) are
also accessible:

document.anchors
document.body
document.documentElement
document.embeds
document.forms
document.head
document.images
document.links
document.scripts
document.title
Changing the HTML Output Stream
JavaScript can create dynamic HTML content:
Date: Tue Aug 17 2017 11:00:42 GMT+0800 (Philippine
Standard Time)
In JavaScript, document.write() can be used to write directly to the
HTML output stream:

Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
Changing the HTML Output Stream
Never use document.write() after the
document is loaded. It will overwrite the
document.
Changing the Value of an Attribute
To change the value of an HTML attribute,
use this syntax:

document.getElementById(id).attribute = new
value
Changing the Value of an Attribute
This example changes the value of the src attribute of an <img>
element:
Example
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
Changing HTML Elements
Method Description
element.innerHTML =  new html Change the inner
content HTML of an element
element.attribute = new value Change the attribute
value of an HTML
element
element.setAttribute(attribute, value) Change the attribute
value of an HTML
element
element.style.property = new style Change the style of an
Adding and Deleting Elements
Method Description

document.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(element) Replace an HTML element

document.write(text) Write into the HTML output stream


Adding Events Handlers
Method Description
document.getElementById(id).onclick = Adding event
function(){code} handler code to an
onclick event
XML DOM
<?xml version="1.0"?>
<product>
<products> <name>XML Book</name>
<product> <price>19.99</price>
</product>
<name>XML Editor</name> <product>
<price>499.00</price> <name>XML Training</name>
<price>699.00</price>
</product> </product>
<product> </products>
<name>DTD Editor</name>
<price>199.00</price>
</product>
XML DOM Diagram
An Application of DOM
><HTML>
<HEAD>
<TITLE>Currency Conversion</TITLE>
<SCRIPT LANGUAGE="JavaScript" SRC="conversion.js"></SCRIPT>
</HEAD>
<BODY>
<CENTER>
<FORM ID="controls">
File: <INPUT TYPE="TEXT" NAME="fname" VALUE="prices.xml">
Rate: <INPUT TYPE="TEXT" NAME="rate" VALUE="0.95274" SIZE="4"><BR>

<INPUT TYPE="BUTTON" VALUE="Convert" ONCLICK="convert(controls,xml)">


<INPUT TYPE="BUTTON" VALUE="Clear" ONCLICK="output.value=''"><BR>
<TEXTAREA NAME="output" ROWS="10" COLS="50" READONLY> </TEXTAREA>
</FORM>
<xml id="xml"></xml>
</CENTER>
</BODY>
</HTML
An Application of DOM
• The “Convert” button in the HTML file which calls the JavaScript
function convert(), which is the conversion routine.

• convert() accepts two parameters, the form and the XML island.
An Application for DOM (Example)
<SCRIPT LANGUAGE="JavaScript"
SRC="conversion.js"></SCRIPT>
function convert(form, xmldocument)
{
var fname = form.fname.value,
output = form.output,
rate = form.rate.value;
output.value = "";
var document = parse(fname, xmldocument),
topLevel = document.documentElement;
searchPrice(topLevel, output, rate);
}
An Application for DOM
function parse(uri,xmldocument)
{
xmldocument.async = false;
xmldocument.load(uri);
if (xmldocument.parseError.errorCode != 0)
alert(xmldocument.parseError.reason);
return xmldocument;
}
An Application for DOM
function searchPrice(node,output,rate)
{if(node.nodeType == 1)
{if(node.nodeName == "price")
output.value += (getText(node) * rate) + "\r";
var children,
i;
children = node.childNodes;
for(i = 0;i < children.length;i++)
searchPrice(children.item(i),output,rate);}}
function getText(node)
{return node.firstChild.data
An Application of DOM
• nodeType is a code representing the type of the object.
• parentNode is the parent (if any) of current Node object.
• childNode is the list of children for the current Node object.
• firstChild is the Node’s first child.
• lastChild is the Node’s last child.
• previousSibling is the Node immediately preceding the current one.
• nextSibling is the Node immediately following the current one.
• attributes is the list of attributes, if the current Node has any.
An Application of DOM

• The parse() function loads the price list in the XML


island and returns its Document object.

• The function searchPrice() tests whether the current


node is an element.
An Application of DOM

• The function searchPrice() visits


each node by recursively calling
itself for all children of the current
node.
An Application for DOM

You might also like