Title: DHTML and DOM
1DHTML and DOM
2Style Sheets CSS and CSS2
- W3C recommendation on Cascading Style Sheet
- CSS level 1 specification allows expressing style
of contents - CSS level 2 specification goes further into
- positioning
- use of HTML 4.0
- defining additional tags
3Positioning
- HTML elements are positionable
- You may specify where they should appear
- as part of the style
- position attribute
- position attribute may take
- absolute
- Position based on or relative to the parent
container. Natural document flow ignored. - relative
- Position is relative to the normal document flow.
- static
- element not positionable, maintains normal
position.
4Positioning Context
- Positioning context is a point which corresponds
to (0, 0) for an element - For the HTML document, it starts with the top
left corner of browser window (document area) - When you define a block level element, it defines
a new context for that element - Every thing is now relative to this new context
- You can define a new context by setting the
position attribute
5Absolute vs. Relative
- ltHEADgtltSTYLEgt
- SPAN.l1 positionabsolute left20 top30
- SPAN.l2 positionrelative left20 top30
- lt/STYLEgtlt/HEADgt
- ltBODYgt
- ltDIVgtHello
- ltSPAN class"l1"gttherelt/SPANgt
- ltSPAN class"l2"gt!lt/SPANgt
- lt/DIVgt
Moved with respect to where browser would
have placed it otherwise
With no positioning
only first Positioning absolute positioning
6Positioning Attributes
- position
- style rule for a postionable element
- left
- offset from left edge of positioning context to
left edge of box - top
- offset from top edge of positioning context to
top edge of box - width
- width of absolute positioned elements content
- height
- height of absolute positioned elements content
- clip
- viewable area shape, dimension of an absolute
positioned element - overflow
- for handling contents that exceed height/width
- visibility
- says if element is visible or not
- Z-index
- stacking order of a positionable element
7DOM Document Object Model
- HTML documents are parsed and displayed by
browsers - Fonts and colors may be specified
- To a certain extent position may be specified
- How about dynamically modifying the contents on
the front end? - DOM provides handled into the browser, allowing
us to access various components of the document
at run time
8Document Object Model
- Document class represents an HTML document
- Provides you a write method
- you can generate HTML dynamically on the
client-side - Documents properties
- alinkColor
- anchors
- applets
- bgColor
- cookie
- Domain
- embeds
- fgColor
- forms
- images
- lastModified
- linkColor
- links
- referrer
- title
- URL
- vlinkColor
9Scripting Events
- Various types of events are generated
- Types of events depends on the positionable
element - Event handler may be specified as an attribute of
the element - For certain events, returning
- true will result in browser continuing with its
usual behavior - false will result in browser ignoring the rest of
action
10Dynamic Techniques
- DOM allows us to address elements
- Event allows us to respond to activities
- Scripts can effectively
- provide event handlers
- access elements using DOM
- Dynamic content generation on the front end for
data validation and varying presentation and style
11DOM
- Browser exposes the object model of the document
for you to manipulate - The Document Object Model
12The structure of a document
- An XML document contains
- data and
- information on the data (Meta information)
- XML document contains
- the contents and
- structure
- What is the structure?
- the types of items it contains
- elements, child-elements, attributes, content
data - relationship between these items
- Which element is the parent of a child element
- what are its attributes
13Grove
- Grove is an abstract model of a structure
- It is the concept and representation of the
structure of an XML document - It represents a tree view of
- Elements
- the child elements
- the attributes
- their values
- content data
- etc.
- Grove is a model not an API of any kind
- information on structure not mechanism to access
it - various APIs used to access and manipulate these
models
14Object Model
- Methods, properties provided to access a
structure - The interface is the key
- Hides the details of structure from programmers
- Interface based programming allows one to
- Access the details of an abstraction
- Without depending on the specifics of the
abstraction
15What is DOM?
- How do you access an XML document?
- Need to parse and extract information among meta
information - DOM is an interface/API for such access
- Language and platform independent
- Specification that may be implemented in any
language - It provides the flexibility to read a document,
to modify, to search it, to add on to it and
remove from
16What does DOM provide?
- If you were to deal with a document, you are
looking at the physical layout of its content - How many elements does it have?
- How do you add an element?
- Read through all elements and get to the end and
append! - How about a logical view of the document?
- You can easily understand the structure
- You can easily manipulate the structure using
an interface/API
17Why use DOM?
- DOM parses and builds all information into memory
- DOM
- Validates well-formedness and grammar
- Using DOM to create a document guarantees
correctness of format - Provides logical/object view hiding the details
- You can rely on the logical view rather than
reading through file structure and tags - Helps it easy to manipulate the document
- You dont have to endure the pain of parsing
- You can rely on API to read
- Lets you delete arbitrary items from the document
18Drawbacks of DOM
- DOM ends up taking more memory
- Much larger than the size of the document
- Reads and builds information on the entire
document - Not efficient for lookup of subset of information
- Entire tree built, whether you need it or not
19API for DOM
- DOM is a specification of Interface
- Several APIs implement this interface
- Comes in different flavors
- Watch out for parsing large sized documents
- May take up too much memory to store large
documents - Some implementations provide just-in-time
extraction to manage large size data, at expense
of additional seek and retrieval time
20DOM aids document interchange
- Provides effective method to exchange Platform
independent self-describing data - Robustness and validation
- Illustrates the relationship between data
elements that may not otherwise be obvious
Application
Application
21DOM facilitates data archival
- Text formed data can be easily archived, parsed,
compressed and transferred - The contents of a data store may be archived for
later use or reference purpose - Applications (like mail program) may use this for
archiving older mails/records - Useful for initialization/configuration
information as well
22Meaningful presentation of data
- Client systems may interact with the DOM nodes to
decide and to eliminate information that may or
may not be relevant - By packaging the information with the semantics,
client programs can put the information to better
use - Systems may aid user with selective utilization
of information
23A common data exchange gateway
App5
App4
App3
App0
App1
App2
App5
App4
DOM
App0
App3
XML
App2
App1
24W3Cs DOM
- platform- and language-neutral interface that
will allow programs and scripts to dynamically
access and update the content, structure and
style of documents - Level 0
- Functionality of Netscape 3.0 and IE 3.0
- Level 1
- Navigation and manipulation of HTML and XML doc
- Oct. 1 1998
- Level 2
- Support for namespaces, plus changes to
interfaces - Nov. 13, 2000
- Level 3
- Work under progress
25The Tree Model
- XML by nature provides relationships
- Parent child relationship
- This ideally falls into a tree model
- Parent nodes connecting to child nodes gives
logical view of data - Easy to conceptualize
- Easy to abstract and model
Nodes
Parent
Child
Child
26The Tree Model as seen from IE
27Node and Node Types
- A Node is a base type that is a generic node in
the DOM Tree view model - Several types of specific node types exists
- You will never create node of simply the type
Node - You may treat all nodes as type Node, however
28Document Node Types
- Document
- The master node
- Parent node representing the document as a whole
- Does not represent any specific piece of XML data
- Allows creation and insertion of other nodes
- Only one can exists in an XML document
29NodeList Node Type
- NodeList
- Holds a collection of child nodes
- Can provide information about child nodes
- like how many is contained
- Main purpose is to provide information and access
to child nodes
Parent
Parent
NodeList
Child
Child
Conceptual Model
Child
Child
DOM Model
30NamedNodeMap Node Type
- Much like the NodeList in functionality
- Provides the ability to access child nodes by
name - Needed for accessing attributes
- Typically attributes are lookup by their names
- Used to hold attribute nodes
31Element Node Type
- Element node represents an element in XML doc
- Each child element has a parent element node
- Except topmost element node whose parent is the
Document node - Each element may have optionally child elements
- Top most element is given special name
- documentElement
32Text Node Type
- Represent the text contained within element tags
- This is what makes the content of the element
- The PCDATA types
33Attr Node Type
- Generally specified within element
- Represents attributes within scope of elements
- Also used in Entity and Notation nodes
34Tree Model with Elements, Attributes
- Consider
- ltCataloggt
- ltBook material"paper" cover"paperback"gt
- ltTitlegtApplied XMLlt/Titlegt
Document Node
35CDATA Section Node Type
- Similar in nature to the Text node
- Contains data that does not contain any markup
- Arbitrary non parsed text makes up this
36DocumentType Node Type
- This represents a subset of what you put into DTD
- This object provides you access to the DTD of a
doc - Only ENTITY and NOTATION of DTD exposed
- Known limitation of DOM
- Child of the Document node
- Parent to Entity node and Notation node
37EntityReference Node Type
- EntityReference node represents a reference to an
entity that is declared in DTD - It contains a Text node
- However
- Text nodes under EntityReferences are read-only
- Pretty much use less since you cant change this
38A few other Node Types
- ProcessingInstruction
- Represents a PI in a document
- This is a child of the Document node
- Comment
- Represents a comment node
- DocumentFragment
- Stripped down version of Document node
- Used as place holder when moving nodes around
- Simply temporary storage of nodes to be
reinserted into the tree
39DOM API
- DOM API comes in different languages and flavors
- We will see the DOM API using JavaScript
- Other scripting languages may also be used
- The API pretty much maps over to other scripting
languages and programming languages
40var in JavaScript
- JavaScript is not a strongly typed language
- var refers to a variable that may be assigned any
variable or object - It may be assigned just about any thing of any
type - In case of xml data island, the id represents the
Document node
41Data Island Options
- In an HTML file you may
- Contain an XML file within
- Refer to an external XML file
- ltXML ID"xmlID101"gt
- lt!-- content of the XML filegt
- lt/XMLgt
- Multiple data islands may appear with unique IDs
- var docNode anID
- Refers to a DOM document node object
42Accessing XML DOM Node
- Three ways to access an XML DOM node
- The ID represents a document Node
- var docNode xmlID101
- The ID treated as HTML object models all
collection - var docNode document.all("xmlID101")
- You may obtain using the XMLDocument property
- var docNode document.all("xmlID101").XMLDocument
43Using an independent XML DOC
- IE5 provides an XML parser as an ActiveX object
- The CLSID for the parser maps to the program
alias - "microsoft.xmldom"
- You may create an XML Parse object by calling
- var parse new ActiveXObject("microsoft.xmldom")
- You may want to set parse.async false to
disable synchronous downloading - You may call load method to load your XML doc
- Then use the functions on the Document object
44Accessing an external XML Doc
- You may place a XML within HTML
- data island
- You may also refer to an XML file outside
- Simply
- invoke the parser
- ask it to load/parse external file
- The document node object now refers to parsed
external XML document
45Displaying Document Node Info
- The xml id represents the document node
- We can create a variable that refers to this id
- This is a reference or handle to a Document node
object - You can now call documentElement to get to the
root element - nodeName will tell you the name of the node
46Classes in DOM API
47Node Property nodeName
- String name of node effect depends on type of
node - Document document
- Element tag name
- Attribute attribute name
- Text text
- CDATASection cdata-section
- Comment comment
- Entity entity name
- Notation notation name
- EntityReference name of entity reference
- ProcessingInstruction target
- DocumentType document types name
- DocumentFragment document-fragment
48Node Property nodeValue
- String data of the node effect depends on type
of node - Attribute attribute value
- ProcessingInstruction text (following target)
- Comment comment text
- Text text
- CDATASection text
- Other nodes null
49Node Property nodeType
- int type of
- The type of node and the corresponding int are
- 1 Element
- 2 Attribute
- 3 Text
- 4 CDATASection
- 5 EntityReference
- 6 Entity
- 7 ProcessingInstruction
- 8 Comment
- 9 Document
- 10 DocumentType
- 11 DocumentFragment
- 12 Notation
50Node Property ownerDocument
- DocumentNode Document node in which the current
node resides - Returns access to the highest level parent of any
node - Very convenient for
- creating other nodes
- accessing top level details
51Node Property Accessing Other Nodes
- childNodes
- NodeList holds collection of children nodes
- If node does not have any children
- then the returned NodeList will indicate a length
of zero - parentNode
- Node node of the parent
- attributes
- NamedNodeMap holds all attributes of given node
- firstChild Node
- lastChild Node
- previousSibling Node
- nextSibling Node
52Node Methods
- Calling on non-supporting node type causes error
- insertBefore(newChildNode, refChildNode) Node
- Inserts before refChild. At end if refChild null
- DOMException thrown in case of invalid node
type, - replaceChild(newChildNode, oldChildNode) Node
- removeChild(oldChildNode) Node
- appendChild(newChildNode) Node
- If newChild is located somewhere else in tree
- it is first removed from that location
- then added to current list
- hasChildNodes() Boolean
- cloneNode(deepBoolean) Node
53Node Properties and Methods (Level 2)
- normalize void
- moved from Element in Level 2
- isSupported(feature String , version String)
boolean - hasAttributes() boolean
- namespaceURI String
- prefix String
- localName String
54Document Property documentElement
- Element node highest level element in the
document - This returns the top most element within the XML
document - The given node is of type Element node
55Document Property doctype
- DocumentType node One that holds subset of DTDs
- Returns the DocumentType object which holds a
subset of the DTDs in the document
56Document Property implementation
- DOMImplementation node the DOM implemetation
- DOMImplementation provides details about version
- Mechanism to perform version checking on the doc
57Document Methods
- createElement(tagNameString) Element
- createDocumentFragment() DocumentFragmen
t - createTextNode(dataString) Text
- createComment(dataString) Comment
- createCDATASection(dataString) CDATASection
- createProcessingInstruction(
- targetString, dataString)
ProcessingInstruction - createAttribute(nameString) Attribute
- createEntityReference(nameString)
EntityReference - getElementsByTagName(tagNameString)
- NodeList
58Document Methods (Level 2)
- importNode(importedNode Node, deep boolean)
Node - createElementNS(namespaceURI String,
qualifiedName String) Element - createAttributeNS(namespaceURI String,
qualifiedName String) Attr - getElementByTagNameNS(namespaceURI String,
localName String) NodeList - getElementByID(elementID String) Element
59Element Property tagName
- String represents the tag name of the element
- This information is the same as the one returned
by nodeName on a Node - For an Element you may use either one
interchangeably
60Element Methods
- getAttribute(nameString) String
- setAttribute(nameString, valueString)
- removeAttribute(nameString)
- getAttributeNode(nameString) Attribute
- removeAttributeNode(oldAttrAttribute)
Attribute - setAttributeNode(newAttrAttribute) Attribute
- getElementsByTagName(nameString) NodeList
- Unlike Documents method, returns only elements
within the sub-tree of current element node, not
whole doc
61Element Methods (Level 2)
- getAttributeNS(namespaceURI String, localName
String) String - setAttributeNS(namespaceURI String,
qualifiedName String) void - removeAttributeNS(namespaceURI String,
qualifiedName String) void - getAttributeNodeNS(namespaceURI String,
localName String) Attr - setAttributeNodeNS(newAttr Attr) Attr
- getElementsByTagNameNS(namespaceURI String,
localName String) NodeList - hasAttribute(name String) boolean
- hasAttributeNS(namespaceURI String, localName
String) boolean
62Attribute Properties
- nameString
- specifiedBoolean
- true if this attribute was specified in the XML
document - valueString
- ownerElement Element
- Introduced in DOM Level 2
- gives the element to which this attribute belongs
63NodeList Properties and Methods
- length unsigned long int
- item(indexunsigned long integer value)
- Zero based index is used
- On IE5, a shortcut theNode.childNodes(index) may
be used instead of theNode.childNodes.item(index)
64NamedNodeMap Properties Methods
- length unsigned long integer
- getNamedItem(nameString) Node
- setNamedItem(nodeNode) Node
- If another node with name same as given node
exists - replaces that node
- Exception thrown if
- given node created in another document(OK in IE5)
- if read-only or given node in another element
- removeNamedItem(nameString) Node
- item(indexunsigned long integer value) Node
- Level 2 methods
- getNamedItemNS(namespaceURI String, localName
String) Node - setNamedItemNS(arg Node) Node
- removeNamedItemNS(namespaceURI String,
localName String) Node
65CharacterData Properties, Methods
- dataString
- lengthInteger
- substringData(offsetunsigned long,
countunsigned long ) String - appendData(appendStringString)
- insertData(offsetunsigned long,
newStringString) - deleteData(offsetunsigned long, countunsigned
long) - replaceData(offsetunsigned long, countunsigned
long, dataString)
66Text Methods
- splitText(offsetlong) Text
- Produces two text nodes from the text node on
which it is called - First text node has characters from index 0 upto
given offset - Second text node has characters from offset point
to the original length 1
67CDATASection Comment
- CDATASection
- is identical to Text as it derives from it
- no new properties or methods
- Comment
- is identical to CharacterData
- no new properties or methods
68DocumentType properites, Methods
- nameString
- Name of the root document that follows DOCTYPE
- Read only access provided to this
- entitiesNamedNodeMap
- notationsNamedNodeMap
- No methods to manipulate any of these
69Entity/Notation properties, Methods
- systemidString
- This is what follows the SYSTEM declaration
- If not present, will return null
- publicidString
- This is what follows the PUBLIC declaration
- If not present, will return null
- The above two methods are also for Notation
- notationNameString
- Name of notation for unparsed entities
- (null for parsed ones)
70EntityReference, ProcessingInstruction
- EntityReference does not add any more than Node
- ProcessingInstruction
- targetString
- dataString
71DOMImplementation Methods
- hasFeature(featureString, versionString)
Boolean - If specified version exists for the specified
feature, return true otherwise returns false - Valid values as of now are
- HTML and XML
- Current version of XML is 1.0
72DOMString
- DOMString is really used to represent String
- Based on language, it will map to String, BSTR,
etc. - It represents a 16-bit unicoded entity rather
than a byte
73DOMException
- This is the exception class used in methods that
throw exceptions - This maps to language specifics, as well
74MS Extensions for DOM
- Microsoft XML Parse provides extensions to the
DOM model by adding support for - Data types support
- Defines several data types like date, int, etc
for validation - Namespace support
- You can request for qualified name, prefix, URI
- XSL support
- transformNode() method applies XSL transformation
- Asynchronous downloads
- async (enable/disable async download)
- readyState and parsed (describe state of
document) - abort (abort async download and discard loaded
document) - Thread safety support (Free threaded and rental
model) - Microsoft.FreeThreadedXMLDOM may be used to
create ActiveX object - xml property lets you persist XML tree
- allows modification and save
75MS DOM Interfaces
- Similar to DOM interfaces, start with IXMLDOM
- Provides additional properties and methods
- IXMLDOMNamedNodeMap, IXMLDOMNodeList
- IXMLDOMParseError, IXMLDOMImplementation,
IXMLDOMHttpRequest - IXMLDOMNode
- IXMLDOMDocumentFragment
- IXMLDOMAttribute
- IXMLDOMElement
- IXMLDOMDocument
- IXMLDOMDocumentType
- IXMLDOMNotation
- IXMLDOMEntity
- IXMLDOMEntityReference
- IXMLDOMProcessingInstruction
- IXMLDOMCharacterData
- IXMLDOMText, IXMLDOMCDATASection, IXMLDOMComment
Here we address Some of the interesting
/important ones
76IXMLDOMNodes xml
- xml String
- This produces an XML document starting from the
current node - The XML document formed is useful for saving an
XML document that has been manipulated using DOM
77IXMLDOMNodes text
- text String
- Contents of the node concatenated with all the
contents of the nodes found in the childNodes
collection - For nodes with no children, simply returns the
value of that node
78IXMLDOMNodes parsed
- parsed Boolean
- Tells whether the node and its children have been
parsed - Useful in the case of asynchronous loading of XML
documents
79IXMLDOMNodes transformNode()
- transformNode(stylesheetNode)String
- This methods applies the given stylesheet
transformation on the current node - The result String contains the transformed XML
- Pretty useful to apply one of select few
stylesheets on an XML document
80IXMLDOMDocument Properties
- url String
- If load() was used, this returns the URL location
of doc - parseErrorIDOMParseError
- Error object for this document
- readyStateLong integer
- State of downloading and parsing progress
- States are UNINITIALIZED, LOADING, LOADED,
INTERACTIVE, COMPLETED - asyncBoolean
- true for asynchronous loading
- validateOnParseBoolean
- tells if the parser should check if the document
conforms to DTD - preserveWhiteSpaceBoolean
- resolveExternalsBoolean
81IXMLDOMDocument Methods
- load(urlString)Boolean
- loadXML(xmlString)Boolean
- An XML document itself given as String, loaded,
parsed - save(destinationString or IXMLDOMDocument or
ASP Response object) integer - Saves the DOM tree to specified location
- Intended for use on the server
- Browse security will limit its usage on client
side - createNode(typeint, nameString,
nsURIString)Node - nodeFromID(idString)Node
- abort()
82IXMLDOMNodeList Methods
- nextNode() Node
- Returns the first node first, subsequent nodes
follows - reset()
- Reset the iterator like nextNode() method so the
next call would start at first method again
83IXMLDOMNamedNodeMap
- getQualifiedItem(nameString, nameSpaceString)No
de - removeQualifiedItem(nameStirng, nsString)Node
- nextNode()Node
- reset()
84IDOMParseError
- errorCodeLong integer
- Error code of last parsing error
- urlString
- URL of the XML document with parsing error
- ReasonString
- Reason for the last error
- srcTextLong integer
- Returns line of text on which parse found error
- lineLong integer
- Line number where parse found error
- linePosLong integer
- Column number of error location
- fileposLong integer
- Character position of error from beginning of
document