Quick viewing(Text Mode)

Working with DOM Alex Gklinos M.Sc

Working with DOM Alex Gklinos M.Sc

Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Teach yourself

Working with DOM

W3C- DOM The The structure of DOM Management of an HTML document with DOM nodes

Relationships and management of document nodes Creating a new node Replacing a node with a new node Deleting an existing node DOM nodes management script of an HTML document

by Alex Gklinos M.Sc. in E-Commerce in 6 hours

Client Side Web Technologies The most cost-effective valuable e-books at w3opensource.com

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Document Object Model

Working with DOM

Learning Document Object Model Working with DOM you will be able to create structure web documents which will cover the browsers versions 6 and later for full compatibility with the W3C-DOM model.

From the 6th version and later all main browsers of the market that are based on the W3C-DOM model offer full compatibility with this object oriented technology for the web documents structure. Knowing the DOM technology in combination with JavaScript you will able to program each HTML or XML element which DOM converts to an object - node achieving perfect performance for your web documents.

Especially you will learn :

How to read an HTML or XML document under DOM How a web document is structured with DOM How the document tree of nodes is created How to manage a web document through DOM How to handle the relationships among the nodes of the web document How to create a new node in an HTML document How to add the id attribute to a new node of a web document How to create contents for new nodes How to embed a new node into the body elemnt of an HTML document How to write script to create and embed a new node into the document How to replace a node with a new node How to delete an existing node How to manage the DOM nodes of an HTML document

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Chapter 1 : Introduction to Document Object Model -DOM

1.1. The Object Management Group & IDL language of W3C 1.2. W3C DOM - The Document Object Model 1.2.1. recommendation of WC3 DOM - Level 1 1.2.2. recommendation of WC3 DOM - Level 2 1.2.3. recommendation of WC3 DOM - Level 3 1.3. The DOM 1.4. The DOM

Chapter 2 : The structure of W3C-DOM

2.1. Access the web document structure through W3C-DOM 2.2. Node is the core of the DOM structure 2.3. The DOM access models of Microsoft and Netscape 2.3.1. The object document.all of Microsof 2.3.2. The object document.layers of Netscape 2.4. The Nodes technology and the family tree 2.4.1. HTML document nodes 2.4.2. XML document nodes 2.4.3. Parents, children & siblings nodes 2.4.4. .Nodes categories

Chapter 3: Managing web documents with W3C-DOM

3.1. Management of an HTML document with DOM nodes 3.1.1. The id attribute in an element of an HTML document 3.2. Relationships and management of document nodes. 3.3. Creating and embedding nodes 3.3.1. Creating a new node 3.3.2. Adding the id attribute to the new node 3.3.3. Creating contents 3.3.4. Adding contents to the new node 3.3.5. Embedding the new node into the body element 3.3.6. Script to create and embed a new node into the document 3.4. Replacing a node with a new node 3.5. Deleting an existing node 3.6. DOM Management script for an HTML document

Chapter 4: The node document

4.1. Properties of node d o c u m e n t 4.1.1. documentElement 4.1.2. doctype 4.1.3. readyState 4.1.4. onreadystatechange 4.1.5. ondataavailable 4.1.6. parseError 4.1.7. url 4.2. Methods of node d o c u m e n t 4.2.1. getElementbyId(id) 4.2.2. getElementsbyTagName(tag) 4.2.3. createTextNode(data)

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

4.2.4. createComment(sxolio) 4.2.5. createElement(name) 4.2.6. createProcessingInstruction(target,data) 4.2.7. createEntityReference(name) 4.2.8. createCDATA(data) 4.3. Accessing a web document through its document node

Chapter 5: DOM Nodes Properties and Methods

5.1. The basic properties of nodes 5.1.2. nodeType 5.1.3. nodeName 5.1.4. nodeValue 5.1.5. attributes methods: reset() - nextNode() - getNamedItem() 5.1.6. text methods: splitText() - insertData() - appendData() replaceData() - deleteData()

5.2. Properties which define relationships among nodes 5.2.1. Relationship property of parentNode 5.2.2. Relationship property of childNodes 5.2.3. Relationship properties of firstChild, lastChild, previousSibling, nextSibling

5.3. General methods of nodes relationships appendChild(child), insertBefore(child,beforechild), replaceChild(child,old), removeChild(child), cloneNode(deep), hasChildNodes(), getNamedItem(), setNamedItem(), removeNamedItem()

5.4. Methods for properties of Element nodes setAttribute (name,value), setAttribute(attr), getAttribute(name), removeAttribute(name), setAttributeNode(attr), getAttributeNode(name), removeAttributeNode(name)

5.5. Changing URLs and the connection text through DOM 5.5.1. The logic of the DOM script 5.5.2. The full coded HTML document with the DOM script

Summary Teach yourself at w3opensource Learn More Our e-Business Web Tutor Environment

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

1. Introduction to Document Object Model

1.1. The Object Management Group & IDL language of W3C

The Document Object Model (DOM),

has not only been created for browsers but also as a multi-language, multi-platform Application Program Interface.

The ΟMG ( Object Management Group ) of W3C has developed the IDL ( Interface Definition Language ), a special language for object interfaces. OMG IDL is not used to describe objects, that is what they do, but what their properties and methods are.

In this way, IDL maps the elements-objects of an Object Oriented Programming language and with the certain DOM standards in IDL, achieves support of multiple languages.

So far, there is an IDL mapping of Java, C++, Ada, Smalltalk and Cobol and the respective DOM standards are available.

1.2. W3C DOM - The Document Object Model

The Document Object Model (DOM), was initially created by the W3C organization aiming at the browsers' compatibility and particularly that of 3 and Explorer 3.

The DOM recommendation supports both HTML and XML documents. The Document Object Model - DOM allows the

z access & add z access & delete z access & manipulate z all styles z all elements z all attributes of a document

The document can be accessed using the DOM through several programming languages that the browser supports, such as :

z Java, z JavaScript / ECMAScript / JScript z and VBScript (MSIE ).

DOM 1 (level-1), defines the full standardization of the document as far as objects are concerned, that is how the objects are structured and how we can refer to them.

You can find the recommendation of the standards of DOM-Level-1 at the site :

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

WWW.w3org/TR/REC-DOM-Level-1/

DOM provides a typical way of accessing the document objects, no matter what the programming language or the browser is, and enables us to develop DOM applications using JavaScript or other programming languages.

The connection of W3C DOM with ECMAScript, which is a standardization of JavaScript, lets us develop applications that support as many browsers as possible.

DOM 2 (level-2), furthermore, defines a system of event handling and the validation of the document through its declaration of its type (DTD - Document Type Declaration).

You can find the recommendation of the standards of DOM-Level-2 at the site :

WWW.w3org/TR/REC-DOM-Level-2/

What follows is the basic DOM terminology :

1. Νode : It's the reference to an element, its attributes or a document text. 2. Element: It represents in any reference a certain document tag.

3. Attribute : It represents a certain attribute of the document element.

Browsers that offer full support of DOM are ΙE 6+ and + and all others which based upon them. These browsers versions enable us to access any code, element or attribute of an HTML element through DOM

Support of multiple browsers from DOM applies only to the versions of the two main browsers we mentioned above. Checking backwards compatibility that concerns older browsers not supporting DOM is left to the programmer either through browser detection or through objects the browser supports (Object Detection).

1.2.1. Recommendation of WC3 DOM - Level 1 (1st October of 1998)

DOM 1 (level-1), defines the full object standards of a web document, how the document object- elements are structured and the ways that we can use to refer to them.

It is implemented in XML and HTML documents.

(This diagram Architecture of the core of DOM Level 1 is from W3C)

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

DOM, offer us a typical access way to document objects independently from the programming language or browsers giving us the possibility to develop DOM applications through JavaScript or other programming languages.

The connection of W3C DOM with ECMAScript, which is the standard of JavaScript, gives us the possibility to develop applications which could be supported from the majority of browsers of the market.

1.2.2. Recommendation of WC3 DOM - Level 2 (13th November of 2000)

To DOM 2 (level-2), additionally declares,

z the implementation of Namespaces model for the document elements (prefix - elements handling)

z the implementation of Range & Traversal models

{ (Range) the treatment of the document content of a specific range with limits that are declared { (Traversal) the creation of a sub-tree of a nodes list of the document and the movement inside it in order to manage it

z the implementation of Εvent Model for event handling and programming

z the implementation of Style Sheets model for the document style handliing

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

(This diagram Architecture of the core of DOM Level 2 is from W3C)

1.2.3. Recommendation of WC3 DOM - Level 3 (7th April of 2004)

DOM 3 (level-3), additionally declares,

z the implementation of XML Base technology, in order to have access to external URLs from inside of XML-DOM documents

z the implementation of XPath language

z the implementation of Load/Save model that permits nodes or DOM documents to load into other documents as well as the possibility to save them for future use from other Web authors. Also this model uses filters for the nodes or the contents of a DOM document. This technology has been influenced by Java especially from the Java API of processing XML documents - JAXP.

z the validation of the document through its type declaration (DTD - Document Type Declaration).

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

(This diagram Architecture of the core of DOM Level 3 is from W3C)

1.3. The Netscape DOM

Netscape for versions before NS 6, had its own document object model. In these versions the Netscape DOM uses as the basic object of an HTML document the object document which was referred as the root element.

The Netscape DOM for each category of the document elements creates a specific array (table) in which all elements that belong to this category are stored while the HTML document is read.

// The following JavaScript statement returns an array (table) with all images of the document.

document.images

// The following JavaScript statement returns an array (table) with all forms of the dcument.

document.forms

// The following JavaScript statement returns an array (table) with all (URLs) of the document

document.links

etc.

To access the paragraph object with the Netscape DOM first we give an id value to the specific paragraph of the document like the following syntax

...

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

and after using JavaScript syntax we access this paragraph object with its name following the Netscape DOM objects hierarchy like the example below.

document.forms[formaB].part1

The previous JavaScript statement tells to that the paragrath we want to access is included in a form with name="formB".

1.4. The Microsoft DOM

Microsoft, for IE versions before IE 5+, had been used its own model of DOM, having as basic object of the HTML document the object document which was referred as the root element.

As second object in its DOM objects hierarchy uses the object-array (table) all in which are stored all tags of the HTML document.

Internet Explorer, express all elements of an HTML document as objects and for this reason demands full tags addressing, that means the reference of id attribute for each tag.

Internet Explorer reading an HTML document stores all tags into the array-object all.

document.all

To access a specific object of the HTML document like the previous example of the paragraph object we have to follow the IE DOM objects hierarchy referring the object name we want.

// Through the full path of objects hierarchy the JavaScript syntax is the following

var object = document.all.par1

// With direct access through the name of the object which is declared by the id attribute inside the tag.

var object = par1

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

2. The structure of W3C-DOM

The core object of the DOM structure is the Node.

z Every tag of a document element is a node object.

z The document objects follow the tree structure.

z At the top of the hierarchy tree (root) is the document object.

z The node objects of DOM inherit their property values from hierarchically higher nodes and can transfer them to hierarchically lower nodes.

z Accessing node objects of DOM is accomplished either through a hierarchical reference of the path of the tree objects down to the specific node object, or by a reference of its name (ID="...") we have assigned to the node object, through the document attributes.

The whole point of DOM is modeling the document. so that every element can be used as an object, regardless of their structure in the document.

The nodes do not represent the organizational structure of the document, but its elements as objects with certain properties, values and methods referring to them.

In languages oriented towards object programming , the data are encapsulated in objects and can be accessed only through their methods. The protection from a direct export and manipulation of data provided by their encapsulation in objects, is part of the object model the DOM supports.

As an object model, DOM provides :

z Interfaces and objects, so that they represent and handle a document. z The literal meaning of interfaces and objects along with their behavior and properties. z The relations between interfaces and objects.

Every document can either contain a node defining its type (doctype) or not :

z In DOM, documents are represented with the logical structure of a tree (tree structure). z There is a root element node which is the root of the element tree of the document. z Through the tree structure of a document we can access its elements by the tree-walking method, which specifies the path hierarchically without any reference to its properties.

DOM provides structural isomorphism :

z If, for the representation of the same document have been used two DOM applications, the same model will be created, according to XML standards. z Some slight differences might occur because of the parser that will read the document and will create the respective DOM object model.

As an example we can refer to the white spaces that the DOM may not accept as contents of

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

the document elements, if they have been cut off by the parser.

The Document Object Model represents XML and HTML documents in tree-structured objects, so that they can be used at object oriented programming.

The DOM is simply a set of Application Program Interfaces and object with a view to handling XML and HTML documents.

2.1. Access the web document structure through W3C-DOM

W3C - DOM, gives the possibility to browsers that are compatible with it , through the method

getElementsByTagName()

to return an array (table) with all tags that an HTML document contains and that they have the same name with the name of the tag that is refered as parameter to the method.

The tag name must be enclosed in double quotes as a string. Applying this method we can get all the document tags, if we set as a parameter the symbol "*".

getElementsByTagName("*")

Then we can have access to any document tag by its specific name id.

In the example of the paragraph

...

through JavaScript syntax we have :

var alltags = document.getElementsByTagName("*");

// A full walk into the object hierarchy ......

var object = document.alltags.par1

and with reference to the specific name id,

// Direct access to the name id ......

var object = document.getElementById("par1")

In DOM - Level 2, the properties of Style Sheets can be accessed via the style property of an HTML element.

Let us suppose we want to change the font for the text of the paragraph

...

, from Arial to Verdana; the syntax of the DOM statement will be :

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

document.alltags.par1.style.font = "Verdana"

We must admit that it is amazing how we can have access to the elements - nodes of the documents and their properties through DOM.

This technique does not apply to IE 5 as it is not fully compatible with DOM - Level 1. As a result it does not support the acquisition of all the document tags with the parameter value ("*") in an array through the specific property :

var alltags = document.getElementsByTagName("*")

which returns zero as a value.

2..2. Node is the core of the DOM structure

The core-object of the DOM structure is the node.

z Each element tag of an HTML or XML document, declares a node object.

z The document objects are organizing following the tree structure.

z First in the objects hierarchy is the document which is the root object.

z The node objects of DOM, inherit the values of their properties (attributes) to the lower hierarchical nodes of them.

The node objects of W3C- DOM, are accessed

z either through the full walk into the object hierarchy till the node-object that we want,

z or through the direct reference to the id value of the node-object that we want.

The main task of the DOM is the document modeling so that every element of them can to be used as an object independently from the document structure.

Nodes do not represent the structure of the document but its elements as objects with specific properties (attributes), values and methods through which we can manage the values of these properties.

In Object Oriented Programming - OOP languages, data is encapsulated into objects and is accessed only through the methods of the objects that they contain it.

W3C-DOM offers data protection to direct exctraction from its encapsulation into objects as the part of the Object Model that it supports.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

2.3. The DOM access models of Netscape and Microsoft

In order to make object oriented documents,

as we have mentioned previously Microsoft and Netscape with the browser of fourth generation created and presented their own document object models - DOMs

Their aim was to change the contents of the elements through CSS Style Sheets properties so that they give dynamic character to HTML documents.

Naturally the access of the document elements as well as the change of their contents and their position on the document had been taken place by JavaScript scripts.

But these DOM models which were embedded in Microsoft and Netscape browsers, were different and incompatible.

The main difference was that Microsoft supported the all object as the second object in the objects hierarchy while Netscape had been supported the object layers.

2.3.1. The object document all of Microsoft

The object document.all is supported by + and from browsers which are based on Internet Explorer like 6+, iCab, Ice, Omniweb 4.2

As we have mentioned above the Microsoft model of DOM, stores to the object-array all the tags of the HTML document while the Internet Explorer reads the document. After the document is loaded we can use JavaScript to access the tags as objects through their properties and apply methods especially written for them.

The following JavaScript statements are identical since both of them assign the value of 200 as content to the property left of style object which is the property of iconA object, that is included as child object to the all object.

document.all['iconA'].style.left = 200; document.all.iconA.style.left = 200;

If the iconA is the id value of an image of the HTML document with the syntax ,

then, when one of the two previous JavaScript statements is executed the image will move to the left 200 pixels.

Microsoft in order to keep backward compatibility with version IE 4 included into the new versions of IE 5 and IE 6 the old DOM.

Thus, while versions of IE 6+ support the W3C-DOM and are considered 100% DOM browsers, if you want backward compatibility for Microsoft browsers for generations of IE 5 and IE 4 you will use the all object to access the objects of the HTML document.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Microsoft keeps its own DOM inside each new version of Internet Explorer and gives it the name of 'DHTML Object Model', For the W3C_DOM which supports gives the name 'Document Object Model'.

2.3.2. The object document.layers of Netscape

The object document.layers is supported from Netscape Navigator 4 and from browsers that are based on Netscape, such as like Ice, Escape, Omniweb 4.2

The Netscape DOM model for Navigator 4, had used the layers object as the main concept in the HTML document.

Through this object Netscape declared the layers on the document.

Netscape 4, supports the tag which is a tag of Netscape and which does not exist in the specifications of W3C for the HTML 4.01 mark up language..

Because none other browser supports this tag you do not use it and inside of it use the tag

in order to create divisions of the document in which you can embed the layers.

Each level or layer which you will define into a

tag , it would be have a style through a CSS style sheet with a specific position (attribute position of style) and a unique name (attribute id of div).

The array-object document.layers[] contains everything that could be consider as layer on the document such as images, forms, etc.

Keeping in our minds that the DOM of Netscape 4, reading the HTML document stores in the array-object layers[] everything that could be consider as layer on the document and sets this array-object after the top object document in the objects hierarchy, we will have to access first the specific layer-object from the array layers[] and after the image or the form that this layer-object contains.

The following HTML code present an image with id="iconA", which is being inside to an layer- object

which is embedded into another layer-object
.

Every browser of the market could be access the image in the code above and change the content of the property left referring its id name through the following JavaScript syntax:

document.zoro.left = 200;

But Netscape 4, consider each layer on the document as a separate document.

The HTML elements which are included into a layer can not be accessed through the objects hierarchy of the hole document but only through the hierarchy objects hierarchy of their own level (layer).

In the HTML code above, we suppose that the first level (Layer) which is defined with the

tag had been declared with an absolute position through a Style Sheet.

To have access through DOM of Netscape 4, the layer we will have to write one of the two following JavaScrip statements:

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

document.mask.document.zoro.left = 200; document.layers['mask'].document.layers['zoro'].left = 200;

2.4. The Nodes technology and the family tree

DOM, as an application program interface (API), uses the nodes technology to describe the structure and the contents of a document.

Every HTML document element as well as its contents are represented by a certain DOM node. Have a look at the structure of the HTML document that follows :

Document: DOM_familyTree.

DOM structure

DOM is the web standard of writing documents.

Every element of an HTML document is a node - element in DOM structure and is defined with an opening and a closing tag. Every text in an HTML element is also a text - node.

If the document contains only opening tags such as
, ,


etc., they are also treated as nodes standing on the branches of the hierarchy tree and can generate new nodes.

The HTML element defines the document node since it contains all other elements and their contents. This node is the parent of nodes - children head and body,which are siblings.

The node hierarchy levels are defined according to the number of node contained in other nodes, etc.

Have a look at the DOM diagram of the HTML document of our example :

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

(Diagram 1 : dom_structure)

The dotted lines denote the same hierarchy level and that certain nodes have the same parent and are therefore siblings.

2.4.1. HTML document nodes

All the element tags of the HTML document that follows are nodes of the DOM structure as well as the texts, where they exist.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Document : domHTML.html

dom HTML

Table

web

tutor

The diagram that follows represents the DOM structure of the document as well as the relations between its parts based on their being in different hierarchy levels that constitute its branches.

( Diagram 2: dom_HTML )

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

The hierarchy in the object structure is presented in different colors per level. The DOM demands every document element to complete its markup with a closing tag.

2.4.2. XML document nodes

All the element tags of the XML document that follows are nodes of the DOM structure as well as the texts, where they exist.

Document: domXML.xml

DOM A.Gklinos 25.00 XML G.Allen 32.00 CSS F.Penoy 22.00

In the diagram that follows we represent the previous XML document in a DOM model.

The node concerning the declaration tag of the type of the document doctype ( that it is an XML document) is the XML node right after the document node.

The root element node of the document is the node books.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

( Diagram 3: dom_XML )

2.4.3. Parents, children & siblings nodes

In JavaScript, objects containing other objects are called their parents and the contained objects are their children.

The DOM follows the same terminology so that it can refer to nodes containing other nodes, containing other nodes, etc.

DOM, furthermore, characterizes as siblings the node objects that are on the same hierarchy level and are contained in the same node object- that is they have the same parent.

In diagram 2 - dom_HTML, the node objects h2, p and table are siblings since they are on the same hierarchy level and have the same parent, the node object body.

On the other hand, the node objects "Table", "web ", tr and tr , while they are on the same hierarchy level, they are not all siblings - only the tr and tr since they have the same parent, the node object table.

The texts contained in the document elements are text node objects and therefore are children of the node objects that contain them.

The texts "Table" and "web" are children of the parent node objects h2 and p respectively.

Just as the node object "doc12" has the element title as a parent node object.

In diagram 3 - dom_XML, which represents the objects model DOM for the XML document, following the tree structure hierarchy we have as children objects contained in other objects ,like book (b1), book (b2) and book (b3) which are children of the node books and are parents of the

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

nodes title, author and price.

The children of the nodes book (b1), book (b2) and book (b3) are siblings but they are not siblings to the children of other nodes.

Through the relationships of parents - children nodes the model applies the communication and the transfer of the values of their properties.

Our reference to node objects through their relationships is performed with special methods which we will present later.

With certain methods we can also add and remove node objects from a document.

2.4.4. Nodes categories

As we have already mentioned the core of the DOM structure is the node.

DOM organizes the contents of a document as node objects part of the tree structure.

Nodes, as generic objects, are categorized according to what they declare in the document, as for example elements nodes, attributes nodes, text nodes, comment nodes, processing instruction nodes, etc.

In the following table we present the coding that can characterize a node in DOM.

Table of node codes per type, name, value and attributes.

Νode Node Type Node Name Node Value Attributes Code

1 tagName null NamedNodeMap (Element) value of node 2 attribute name - Αttr null (Αttr) attribute contents of a text 3 #text null (Τext) node contents 4 (CDATA) #cdata-section of the CDATA null declaration name - entity 5 null null (Entity Reference) referenced

6 name - entity null null (Εntity)

contents 7 (Processing target null regarding the target Instruction) contents 8 (Comment) #comment regarding the null comment

9 #document null null (Document)

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

name - document 10 null null (Document Type) type

#document- 11 (Document null null fragment fragment)

12 name - notation null null (Notation)

(table - 1)

All the above node types are DOM objects since they are elements that can be contained in an HTML or XML document.

z The attribute Attr, denotes a node attribute and represents an attribute of a node element.

It is not a node child of the node element it describes and therefore DOM does not consider it part of the document tree. So, the attributes that concern node family relations (parentNode, previousSibling, nextSibling) do not apply to nodes-Attr and return null as a value.

z The processing instruction, can be found in any part of the document as long as it is not inside another markup. Markup in XML documents starts with .

css" ?>

The previous processing instruction tells the browser to use the cascading style sheet found in the file "books.css" .

z The CDATA section, creates markup in XML documents with the tag

z The Entity can either be an external file whose data we want to link to our document, or a text block which we define as an entity because we use it frequently in our document.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

3. Managing web documents with W3C-DOM

3.1. Management of an HTML document with DOM nodes

The Document Object Model - DOM,

represents the HTML document in a tree structure.

Each node of the tree declares an HTML tag or some textual entry as contents of an HTML tag.

The whole HTML document can be described through the tree structure, which also specifies the type of relationships among the nodes as far as hierarchy is concerned :

z parent - node z child - node - sibling - node

DOM enables us to navigate into the HTML document and access any markup tag or text it may contain, either using the hierarchy walk method or a direct access method (by tag or id name) with reference to the the certain tag name or its name (id).

The application of properties and methods is common for every node - tag of the document, according to the node type.

The capabilities DOM provides us as far as inserting new nodes in the document, deleting existing nodes and updating the nodes contents are concerned, make DOM the indisputable system of document management.

DOM treats the HTML document as a file of objects with certain markup and information and controls it through JavaScript, object oriented programming principles and methods of file management such as node input, node update and deletion.

3.1.1. The id attribute in an element of an HTML document

DOM specifications require that every tag

of an HTML document, is characterized by a specific name which is assigned as content of the id attribute. The nodes of the document are recognized by this name in DOM.

...

Netscape and Microsoft, trying to turn elements of a document into objects with the early browsers, presented their own document object models so that the limited markup language called HTML can function at least parametrically through JavaScript as an object oriented language.

Netscape, in their own document object model, before versions NS 6+, uses document as the root element and for every document element creates the respective array where all similar elements are stored when the document is read.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

// Returns an array with all the images of the document.

document.images

// Returns an array with all the forms of the document.

document.forms

// Returns an array with all the links of the document.

document.links etc.

The access to an object of the paragraph

...

, presuming it is contained in one of the document forms under the name "formaB" is :

document.forms[formaB].part1

Microsoft, with their own document object model in versions before IE 5+, uses document as the root element and the object all as the second object in the object hierarchy where all document tags are stored.

Internet Explorer, treating all HTML elements as objects, requires a syntax of addressing the tags, that is reference to the id attribute in every tag.

All HTML document tags are stored in the array object all

document.all

The access to a certain tag - object with IE is :

var object = document.all.par1 // A full walk into the object hierarchy

and with reference to the specific name id,

var object = par1 // Direct access to the name id.

W3C - DOM enables browsers compatible to it, through the method getElementsByTagName(), to return an array each time with all the tags contained in an HTML document and have the same tag name with the parameter in the parenthesis.

The tag name must be enclosed in double quotes as a string. With the previous method we can get all the document tags, if we set as a parameter the symbol "*".

if (document.getElementsByTagName("*")) { var alltags = document.getElementsByTagName("*") }

With the previous script we assigned all tags of the document elements to the object - variable alltags.

Then we can have access to any document tag by its specific name id ; in the example of the paragraph

...

, we have : var object = document.alltags.par1 // A full walk into the object hierarchy ι

and with reference to the specific name id,

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

var object = document.getElementById("par1") // Direct access to the name id.

In DOM - Level 2, the properties of Style Sheets can be accessed via the style property of an HTML element.

Let us suppose we want to change the font for the text of the paragraph

...

, from Arial to Verdana; the syntax of the DOM statement will be :

document.alltags.par1.style.font = "Verdana"

We must admit that it is amazing how we can have access to the elements - nodes of the documents and their properties through DOM.

3.2. Relationships and management of document nodes

Every node of the HTML document has a parent node, except for the document node that refers to the whole document with its constituents and is actually the root of the tree.

The relationships among the nodes are defined by the organization and syntax of the HTML elements and the texts they may contain. The node types that are mainly used in HTML documents are node elements and node texts.

Each node can have no, one or more siblings which are nodes at the same level and share a common parent, as well as no, one or more children which are nodes contained in the specific node. In our example :

The node html is the basic node element of the document, with no siblings nodes but with two children nodes head and body. The head and body are siblings since they belong to the same hierarchy level and share a common parent node - node html. The node body contains a child node, the node element p. The node p contains three children nodes, of which only node b is an element node type while the other two are text nodes. The node b contains a text node.

In the table that follows we show the relationships among the DOM nodes according to the document structure :

Implementation of property relationships DOM nodes of HTML document

DOM document HTML title p b properties

nodeType 9 1 1 1 3

nodeName #document html title p #text

"the web nodeValue null null null null standard"

parentNode null document head body b

previousSibling null null null null null

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

nextSibling null null null null null

"DOM is" "Initial head b childNodes html DOM null body "of writing page" documents."

"Initial firstChild html head DOM "DOM is" null page"

"Initial "of writing lastChild html boby DOM null documents." page"

(Table -2)

When ΙΕ 5 opens an HTML page, it creates its own programming object known as Data Source Object (DSO), where it stores the elements hierarchically and provides access to them.

D S O stores the HTML page elements as a record set - a collection of records along with their fields that represent their properties.

But ΙΕ 5, as far as its compatibility with DOM is concerned, does not treat the HTML document itself as a node in the tree structure.

Therefore the DOM properties that refer to the node document of the previous table do not apply to IE 5 and return "undefined", except for the property document.childNodes.

The property nodeValue is applied on text nodes and returns their text contents. Its application on element nodes always returns null as a value.

The properties innerHTML, innerText, outerHTML and outerText are properties of Internet Explorer and are not part of DOM. Modification of the contents of HTML element nodes is accomplished using the methods of DOM node - objects.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

3.3. Creating and embedding nodes

3.3.1. Creating a new node in a HTML document

The creation of a new node,

in the DOM structure of the HTML document is done with the method createElement ("tag") of the object document .

The string that is declared as a parameter contains the element tag we want to create and add in the DOM structure of the document.

The syntax of a new node creation is :

var newNode = document.createElement("P");

The statement above creates a new object called newNode in the computer memory, without it belonging in the DOM structure of the document or acquiring parental or other relations to other nodes in the tree hierarchy of nodes.

Furthermore, we haven't yet assigned an attribute or contents to the object node newNode, actions that follow right away.

3.3.2. Adding the id attribute to the new node

There are two ways to add the id attribute to DOM nodes,

z The simple way of assigning a specific name to the id attribute of the node - object,

newNode.id = "neoPar";

z and through the method setAttribute() on the DOM element - nodes,

newNode.setAttribute("id","neoPar");

In both cases we have defined the id attribute for the object - node newNode under the name of "neoPar"which means that through a script we can have direct access to this node by using its name "neoPar".

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

3.3.3. Creating contents

The creation of text content ,

into the new node newNode,requires the creation of a text node where the certain text will be assigned to.

This is done through the method createTextNode() of the node object document, which creates a node that will contain text, following the syntax :

z creation of a Text Node

var newText = document.createTextNode();

z assigning the text to the property Node Value

newText.NodeValue = "DOM is indisputable..." ;

or by the simultaneous creation of a Text Node along with the assignment of Node Value to it :

var newText = document.createTextNode("DOM is indisputable...");

3.3.4. Adding contents to the new node

The text node newText we created and which we assigned a certain text to as its content, must be embedded, that is contained in the new node newNode we created and want to append to the DOM structure of the DOM_Insert_Paragraph.html document.

This means that the relation between the two nodes is that of a parent newNode to child newText and will be able to work by applying the method appendChild() to append the new node text node newText , as a child node of the node newNode, following the syntax :

newNode.appendChild(newText)

By appending the new text node as a child node of the node newNode, we will have :

DOM is indisputable ...

All we have to do is to decide in which part of the document DOM_Insert_Paragraph.html this structure will be embedded and define its relation to the other nodes of the document according to the family hierarchy.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

3.3.5. Embedding the new node into the body element

The hierarchy level of the document nodes,

where we want to embed the new node defines the relations of the new node to nodes of the same, upper or lower level.

The embedding method is appendChild() and the hierarchy level where we will append the new node is inside the document body, that is inside ... .

That means that the new node newNode will have the node as a parent node and the node

...

as a sibling node.

The syntax of appending it into the node object is :

document.body.appendChild(newNode)

The path of the DOM hierarchy structure of the document must be followed with every detail so that the new object - node is appended as a child node to the node we aim at.

The representation of the nested levels in the family tree of the nodes after appending the new node newNode, will be :

document

-- -- -- --"Initial DOM page" --<body> --<p id="par1"> --"DOM is" --<b id="bold1"> --"the web standard" --"of writing documents" --<p id="neoPar"> --"DOM is indisputable... " </p><p>3.3.6. Script to create and embed a new node into the document </p><p>The Script, that sums up all of the above creating a new paragraph with a certain text which then is embedded into the document DOM_Insert_Paragraph.html is the function insertParagraph(), which we call and execute with the event handler onclick in the element <button>. </p><p>Here is the code : </p><p>Document: DOM_Insert_Paragraph.html</p><p>Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce </p><p><!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <meta name="Author" content="A. Gklinos" /> <meta http-equiv="Content-Language" content="en"> <title>DOM_Insert_Paragraph

DOM is the web standard of writing documents.

With DOM browser we will have the following output :

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

and clicking the button the new paragraph embedded in the document as in the following screen.

3.4. Replacing a node with a new node

Replacement of a node in the DOM structure of the document, is done with the method replaceChild(node). Before applying the method we must access the node we want to replace,

z either accessing it directly via its specific name,

document.getElementById("par1").replaceChild(newNode, oldText)

z or by specifying it through the hierarchy path of the nodes of DOM structure,

document.body.par1.replaceChild(newNode, oldText)

In both cases we must create the new node newNode beforehand and specify the location of the node to be replaced oldText in the hierarchy structure. This is done by creating the parameters - variables with the statements :

var newNode = document.createTextNode("Document Object Model - DOM ") var oldText = document.getElementById("par1").childNodes[0]

By applying the method replaceChild(newNode, oldText), the first variable - parameter newNode creates a text node and assigns the string value "To Document Object Model- DOM " to it, while the second variable - parameter oldText accesses and brings to memory the node to be replaced by the newNode .

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

There is also a simpler technique of replacing a text node contained in another node of the tree structure by assigning a new string value to the property nodeValue of the certain node as in the statement :

document.getElementById("par1").childNodes[0].nodeValue="Document Object Model-DOM "

We must note here that the property nodeValue applies only to text nodes.

3.5. Deleting an existing node

To delete a node from the DOM structure of the document we use the method removeChild (Node).

We use this method after first accessing it and assigning it to an auxiliary memory variable as :

var oldText = document.getElementById("neoPar").childNodes [0]

Then we apply to this variable the deletion method removeChild(oldText),

z either accessing the node directly via its specific name,

document.getElementById("neoPar").removeChild(oldText)

z or by specifying it through the hierarchy path of the nodes of DOM structure,

document.body.neoPar.removeChild(oldText)

3.6. DOM Management script of an HTML document

A main DOM script which is written in order to manage an HTML document, has to cover the following main functions:

z creating a new node z appending new nodes z removing existing nodes and z replacing existing nodes

The script consists of three functions which are called and executed by the respective onClick handlers of the elements - buttons.

In the function replaceNode(), which replaces the contained text in the first paragraph - node of our document with new text, we refer to the direct way of changing the contents, that is the way of assigning it into the property nodeValue of the specific node,

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

// str = " To Document Object Model - DOM "; // document.getElementById("par1").childNodes[0].nodeValue = str;

Removing the slashes you can activate the previous statements and after you convert the other statements of the function into comments you can run the script in Netscape 6+ and get the expected outcome.

Document:: DOM_management_of_HTMLdoc.html

DOM management of an HTML document

DOM is the web standard of writing documents.





Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Netscape 6.0 & 7.0 & 8.0 and later will have the following output.

The second output is displayed after you click on the button "Insert a new node" twice. Every time we click on this button the respective script is executed and the function insertNode (), adds a new node as the last node in the document structure.

The third output is displayed when we choose to delete the last node we created by clicking on the button "Remove a new node" so that the script of the function deleteNode() is executed. Then we click on the button "Replace a node" so that the script of the function replaceNode(), is executed and replaces the contents of the first paragraph with new.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Then we click on the button "Replace a node" so that the script of the function replaceNode(), is executed and replaces the contents of the first paragraph with new.

Internet Explorer 5+, does not support the method replaceChild() and as a result when the script containing the function replaceNode() is executed, it returns an error message.

Executing only the choices "Insert a new node" - function insertNode()- and "Remove a new node - function deleteNode(), we get the same output as the above screens.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

4. The node document

Now let's talk about the node-object document which is the hiest node-object in the DOM tree structure hierarchy.

It inherits its properties from the node that belongs.

Furthermore, the document node can enter as an independent DOM tree inside of another DOM tree structure, such as when more than one XML documents are embedded in an HTML document.

4.1 Properties of node d o c u m e n t

Properties (attributes) of the node document, are the following :

4.1.1. documentElement

Give us the heist element of the document (topmost element).

RootKomvos = Document.documentElement;

4.1.2. doctype (entities, notations)

Declare the type of the document (document type - DOM level 2).

DocumentType = Document.doctype;

z With property entities, of doctype

we get an array-list-object for example the NamedNodeMap, that contains all entities-nodes for all entity declarations that had been made inside the section of Document Type Definition (DTD) which declares the structure of the document.

NamedNodeMap = Document.doctype.entities;

z applyin the method getNamedItem(attribute name) we have the node property which is ENTITY type with the specific name like the following example:

Entity = Document.doctype.entities.getNamedItem (Attribute.nodeValue);

The Entity node of the example above is created through the name assignment with this method of the specific Attribute entity from the entities list.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

z With property notations

we get an array-list-object for example the NamedNodeMap, that contains all notation-nodes for all notation declarations that had been made inside the section of Document Type Definition (DTD). The syntax is:

NamedNodeMap = Document.doctype.notations;

z applyin the method getNamedItem(attribute name), we get the property node which is NOTATION type with the specific name like the following example:

Notation = Document.doctype.notatios.getNamedItem (NotationName);

The Notation node of the example above is created through the Notation attribute name assingnment witj this method which gets the name from notations list.

4.1.3. readyState

Show us the current status loading and proccessing for an XML document through the following coding values:

( 0: without initial value, 1 : loading process, 2: finish loading, 3: interaction, 4: processing completed.)

if (Document.readyState = 4) // data access completed ...

4.1.4. onreadystatechange

This property of document node, operates as event handler of property readyState. We assign a JavaScript function as value to it which is executed every time the event of changing its value from 1 to 4 takes place.

document.onreadystatechange = TestError();

4.1.5. ondataavailable

And this property of document node, operates as event handler and executes the JavaScript functin which we had assigned as its value while the data of an XML document are being available.

document.ondataavailable = DataFun();

4.1.6. parseError

Give us information for erros that taken place during the XML document processing.

ErrorCode = document.parseError.errorCode;

4.1.7. url

Give us the URL address of the XML document

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

URL = document.url;

The node-object document is the root object, and the first object hierarchically in the DOM tree structure (topmost element) of the document as we have mentioned previously.

An XML parser, reads an XML document and returns it under the DOM tree structure through the document object..

4.2. Methods of node d o c u m e n t

4.2.1. getElementById(id)

Returns the node with the name that declares its parameter.

NodeById = Document.getElementById("alex");

After the execution of the JavaScript statement above the NodeById variable will contain the node of the document with id="alex".

4.2.2. getElementsByTagName(tag)

Returns an array-object with all elements of the document which are represented by the tag that is set as parameter. If we set as parameter the symbol ("*") then we get an array-object with all tags of the document as element nodes.

AuthorSet = document.getElementsByTagName("Author");

The JavaScript statement above creates an array-object (NodeList) with all element type nodes of an XML document with tag name "Author".

To access these kind if nodes you can apply the looping methodology using the loop for as the following code example.

NodeList = document.getElementByTagName("p"); // it gets and assigns all nodes "p" of the document to the array-list NodeList // for ( i=0; i< NodeList.length; ++i ) { alert ( NodeList(i).text ) // displays the content-text of every node "p" which is stored into the NodeList array-list }

With the same way you can access the contents of the property childNodes.

4.2.3. createTextNode (data)

Creates a new Text-node with content the content of its parameter as the example

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

that follows.

var NewTxtNode = document.createTextNode("Hello!");

4.2.4. createComment (sxolia)

Creates a Comment-node with content the content of its parameter as the following example.

var rem = document.createComment("end of discussion");

4.2.5. createElement(name)

Creates an Element-node, with name the content of its parameter like the following example.

var link = document.createElement('a'); link.setAttribute ('href', 'mypage.htm');

In our example above after the creation of our new Element node with id name (id='a')we added a second JavaScript statement in order to set a property (attribute) to this new node. As we are going to use it as a link element we add it with the method setAttribute() the 'href' property with the value 'mypage.htm' witch are the first and the second parameters of the method respectively.

4.2.6. createProcessingInstruction (target,data)

Creates a ProcessingInstruction- node, with target.

var Pr=document.createProcessingInstruction (target,data)

4.2.7. createEntityReference (name)

Creates an EntityReference-node, with name the parameter content.

var komvosERef = document.createEntityReference(name)

4.2.8. createCDATASection (data)

Creates a CDATASection-node, with content the content of its parameter.

var komCDATA = document.createCDATASection(data)

4.2.9. createAttribute (attrName)

Creates an object with name the name of the parameter. After that we can give it through JavaScript a value and add it as a property (attribute) to anyone element node we want.

var attObj = document.createAttribute("attrName");

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

and

attObj.value = "JavaScript";

4.3. Accessing a web document through its document node

In this section of chapter 4, we present DOM syntax examples through JavaScript statements which can be used to access every node or node property (attribute) through the document node ( node type #9).

z Returns the type of the document

document.doctype

z Returns an array - list of all tags - elements of the document

document.getElementsByTagName('*')

z Returns the first - element of the document

document.getElementsByTagName('*')[0]

z Returns an array - list of all div elements of the document

document.getElementsByTagName('div')

z Returns the first div element of the document

document.getElementsByTagName('div')[0]

z Returns the Style properties of the first t div element of the document

document.getElementsByTagName('div')[0].style

z Returns an array - list of all properties of the first div element of the document

document.getElementsByTagName('div')[0].attributes

z Returns the first property (attribute) of the first div element of the document

document.getElementsByTagName('div')[0].attributes[0]

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

z Returns an array - list of all children nodes of the first div element of the document

document.getElementsByTagName('div')[0].childNodes

z Returns the first child node of the first div element of the document

document.getElementsByTagName('div')[0].childNodes[0]

z Returns the next node of the same level with the first div element of the document

document.getElementsByTagName('div')[0].nextSibling

z Returns an array - list with all Style Sheets that the document contains

document.styleSheets

z Returns the first Style Sheet node of the document

document.styleSheets[0]

z Returns an array - list with the CSS rules of the first Style Sheet of the list

document.styleSheets[0].cssRules

z Returns the second CSS rule of the first Style Sheet of the list

document.styleSheets[0].cssRules[1]

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

5 DOM Nodes Properties and Methods

5.1. The basic properties of nodes

DOM nodes properties (attributes) are referred and applied to the respective elements of the document.

At that point we remind you that every node of the document can be accessed by JavaScript.

DOM model like JavaScript is case sensitive to lower and capital letters and you must be very careful when you write DOM scripts using the DOM syntax.

The basic attributes that concern every node to the DOM structure are the following:

5.1.1. nodeType

The nodeType basic property defines the type of the node.

Returns a coding value from 1 to 12, as we have mentioned in the table-1 of chapter 2 in section "Nodes Categories"

example: 1 = Element node, 3 = Text node, 9 = the document node

nodeForm = Node.nodeType;

5.1.2. nodeName

The nodeName basic property returns the name of the category in which the node belongs.

Returns the name of the node and not its identification name (id) ,

Thus:

z for Element nodes it returns the name of their tag, such as p, body, form

z for Document nodes it returns the name #document

z for Text nodes it returns the name # text

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Syntax :

TagName = Element.nodeName;

5.1.3. nodeValue

The basic property nodeValue returns the content of a node that whould be text.

This property give us the Text nodes content and returns null as value in the case that there is no text as content

It can not be applyed to nodes which are not connected with text.

AttributeValue = Attibute.nodeValue; ElementValue = Element.nodeValue;

5.1.4. attributes

The attributes basic property,

creates an array - list object (NamedNodeMap) with all nodes which are type Αttr (attribute nodes) of a specific node

NamedNodeMap = document.documentElement.childNodes(0).attributes

With the syntax above we create an array-list JavaScript variable with the name NamedNodeMap in which are stored all properties (attributes) of the first children node of the root element of the document which is the documentElement.

All attributes of this specific child node childNodes(0) are collected as attribute nodes (node code = 2) and stored to NamedNodeMap object array.

z With property length, of the object NamedNodeMap, we get the number of attribute nodes nodes that the array-list contains as in the following JavaScript statement.

AttrNumber=Element.attributes.length;

Having the length of the object - array we can access through a for loop alll the attribute nodes of the collection like the following JavaScript code:

NamedNodeMap = document.documentElement.childNodes(0).attributes;

for ( i=0; i< NamedNodeMap.length; ++i ) {

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

alert ( " property name of the node: " + NamedNodeMap(i).nodeName + "\n" + " Value of Property : " + NamedNodeMap(i).nodeValue ); }

z Applying the method reset()

the index-pointer is set before from the first node of NamedNodeMap, so that when the method nextNde() is executed the first node to be returned.

Element.attributes.reset();

z Applying the method nextNode(), the node which is returned from the collection of attributes is the next node from the node in which the index-pointer is being set

Element.attributes.reset(); FirstΑttribute=Element.attributes.nextNode();

z Applying the method getNamedItem(attribute name), we get the specific attribute node declaring its name as parameter

Attr_Node = Element.attibutes.getNamedItem ("ΑttributeName");

5.1.5. text

The text basic attribute gives the full content of the relative node and all children Element nodes that contains.

AllText = Element.text;

z With property length,

we get the number of characters of the text which is the node content as the following example:

CharNumber = Text.length;

The methods that follow are implemented only in text-nodes.

z Applying the method splitText(), the content of a text node is separated in two parts. The parameter which must be an integer defines the number of characters that will remain as content in the node after the method is taken place. The second part of the content is assigned to a JavaScript variable as the separated new content.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

new_SubText = nodeTextA.splitText(8);

If the content of the nodeTextA in the example above is "W3C-DOM The web standard" after the execution of the method splitText(8)with parameter "8" we will get the following results:

For the current node,: nodeTextA = "W3C-DOM "

and for the new JavaScript variable, new_SubText = "The web standard"

z Applying the method insertData()

text or the alphanumeric content of a variable is inserted in a specific point inside the content of a text-nod.

nodeTextA.insertData(8, "* hello DOM *");

The first parameter which must be always an integer declares the position of the index-pointer showing from which character of the current content the new content will be added. From the other part the second parameter defines the string that will be embedded as the content.

Assuming that the content of the nodeTextA remains the same as in the previous example "W3C-DOM The web standard" after the execution of the insertData() method with parameters as the abobe values we will get the following result as content of the nodeTextA node:

nodeTextA = "W3C-DOM * hello DOM * The web standard"

z Applying the method appendData(), a text as literal or a string variable is added to the end of the content of a tex-node.

Have a look of the following example supposing that the content of the node nodeTextA = "W3C-DOM The web standard" is unchanged.

nodeTextA.appendData(" for your futeure needs !");

After the execution of the appendData() method with the specific parameter content we will get the following result as new content for the node nodeTextA.

nodeTextA = "W3C-DOM The web standard for your futeure needs !"

z Applying the method replaceData(), we have two possibilities from the one hand to delete a part from the text-node content and from the other simultaneously to add in this position a new text theoretically as long as we want.

Basically the new text substitutes the text which is deleted and covers the empty space. The following example is implemented for the same original content of the node nodeTextA before any action takes place.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

nodeTextA.replaceData(8, 16, ", is perfect!");

The first parameter which must be always an integer declares the position of the index-pointer showing from which character will start the deletion. The second parameter which must be also an integer shows the total number of characters which are going to delete. Finally the third parameter keeps the string content that will substitute the deleted.

After the execution of replaceData() method with the parameter values as the above we will get the following result.

nodeTextA = "W3C-DOM is perfect!"

z Applying the method deleteData(), a specific part (sub-string) of the content of a text-node is deleted.

This is doing based on the two parameters of the method which must be always integer numbers. The first parameter which must be always an integer declares the position of the index-pointer showing from which character will start the deletion. And the second gives to method the total number of characters which are going to delete sequentially.

The following example is implemented for the content of the node nodeTextA the following:

nodeTextA = "W3C-DOM the compatibility model, is the future:

nodeTextA = nodeTextA.deleteData(8, 25);

After the execution of the method deleteData() with the specific parameter values as above we will get the following content for the node nodeTextA.

nodeTextA = "W3C-DOM, is the future:

5. 2. Properties which define relationships among nodes

The properties which define the relationships among notes into the DOM structure based on the family tree hierarchy.

This hierarchy declares the nodes inheritance, that means the transfer of their attributes in nodes that are included inside them as nodes of a lower level.

If a property (attribute) can not be applied in a specific node gets a null value.

For a node which has no children nodes if we use the property firstChild will return a null value.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

5.2.1. parentNode

The parentNode gives the parent of the current node if it's exist . For attribute nodes this property is not valid.

The syntax is:

the_parent = element.parentNode;

5.2.2. childNodes

The childNodes property creates an array-list object, which contains all nodes that are children of a node.

This object array-list is known as NodeList object.

z With the property length,

we get the number of children nodes that are strored to the array-list object. The syntax is:

parentElement.childNodes.length;

Using the property length we can access all children nodes of the childNodes array-list through a for loop as the following example.

for (i=0; i < element.childNodes.length; ++i) { if (element.childNodes(i).nodeType = 3)

text += element.childNodes(i).data; }

To have direct access in a specific child node of the collection into the childNodes array-list you can follow the syntax below:

FirstChild = parentElement.childNodes(0); // returns the first node-child of parentElement LastChilds = parentElement.childNodes(i-1); // returns the last node-child of parentElement

z Applying the method reset(), the index-pointer is set to the node which is been before of the first node of the

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

collection of childNodes array-list, so that when the method nextNode() is executed to return the first child-node of the array-list.

The syntax is:

parentElement.childNodes.reset();

z Applying the method nextNode(),

we get the next node of the childNodes collection array-list from the node in which the internal index-pointer is been set.

The syntax is:

parentElement.childNodes.reset(); FirstChild = parentElement.childNodes.nextNode();

5.2.3. firstChild, lastChild, previousSibling, nextSibling

The childNodes, firstChild and lastChild properties are implemented on children nodes with exception the children nodes of attribute nodes.

For these cases we use the property attributes of the Element node.

With the properties previousSibling and nextSibling, we have the possibility to access any type node in the same level.

z The childNodes property returns the first child node of the current node. The syntax is the following:

FirstChildNod = element.firstChild;

z The lastChild property returns the last child node of the current node. The syntax is the following:

LastChildNod = element.lastChild;

z The previousSibling property returns the node which is in the same level with the current and previous of it. The syntax is:

PreviousNode = element.previousSibling;

z The nextSibling property returns the node which is in the same level with the current and next of it. The syntax is:

NextNode = element.nextSibling;

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

5.3. General methods of nodes relationships

Every node has specific methods which permit access to the nodes that contains either through their attributes or direct with reference in the tag name of the specific code.

The access method which will be selected it depends on the position in which the node is been in the DOM structure. The position that the node holds is very helpful to decide which method we will apply to access it to this specific position.

The node position declares its relationship in connection with the other nodes of the object hierarchy tree structure and for this serious reason it shows the way though it communicate with them.

The appendChild(child) method

adds a new child node to the end of the list of the existing children nodes of the current element node.

The insertBefore(child,beforechild) method

adds a new child node with name the first parameter "child" before from the existing child node which has the name of the second parameter "beforechild".

The replaceChild (child,old) method

substitutes with a new child node with the name of the first parameter "child" the node with the name "old".

The removeChild (child) method

removes the child node with the name "child" from the list of the existing children nodes of the current element node.

The cloneNode(deep) method

creates a new copy node of the current node and if the value of parameter is true creates copies for all children nodes of the current node if it has.

The hasChildNodes() method

returns true value if the node has children nodes and false if it has not.

The getNamedItem(nodename) method

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

returns the specific node which name is declared from the parameter "nodename".

The setNamedItem(nodename) method

sets the specific node which name is declared from the parameter "nodename".

The removeNamedItem(nodename) method

moves the specific node which name is declared from the parameter "nodename"

The array - lists childNodes and attributes which are created from children-nodes and attribute-nodes respectively have common properties and methods.

These are the property length which gives the number of fields of the tables (arrays) and the method item(i), which accesses the specific (i) field of the table. Additionally there are special methods which access nodes by their name which are the methods 7, 8 and 9 above.

5.4. Methods for properties of Element nodes

The methods for Element type nodes, act on properties of Element nodes either to add and delete attributes or to process their contents.

We remind you that every property of a node of the document is an object - JavaScript variable as we use JavaScript with specific content.

Right now you can see analytically the DOM attribute methods , which you can apply to attributes of Element nodes

1. The setAttribute (name,value) method

( is applied on attributes of Element nodes )

creates an attribute with name the value of the first parameter for the current node and gives it as content the value of the second parameter as the following example:

element.setAttribute('born','September.html');

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

2. The setAttribute (attr) method

( is applied on attributes of Element nodes)

Adds the object of the parameter as attribute to the current node element.

AttrNew = element.setAttribute ("born");

3. The getAttribute (name) method

( is applied on attributes of Element nodes )

returns the content of the property with the parameter name.

bornDate = element.getAttribute ("born");

4. The removeAttribute (name) method

( is applied on attributes of Element nodes )

delete the property that its name is declared as parameter from the element nodxe.

bornDate = element.removeAttribute ("born");

5. The setAttributeNode ('name','value') method

( is applied on properties of attribute nodes )

creates an attribute node with name the name that is defined as the first parameter and stores to it the value of the second parameter .

In the follwing example we create a new element node(a) and after we add to it the property href with value the content "mypage.htm":

var link = document.createElement("a"); link.setAttribute("href", "mypage.htm");

6. The getAttributeNode (name) method

( is applied on properties of attribute nodes )

returns the attribute node that name is declared as parameter and which is a property of the specific element node.

Attribute = element.getAttributeNode ("born");

The example above returns the attribute node with the name "born" from the specific node element.

7. The removeAttributeNode (attr) method

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

( is applied on properties of attribute nodes )

delete the property that its name is declared as parameter from the current specific element node

AttrNodeEnd = element.removeAttributeNode ("born");

The example above deletes the attribute node with the name "born" from the specific node element.

5.5. Changing URLs and the connection text through DOM

Using DOM access methods we can change the content any node or property (attribute) node with new one.

To change the URL address of a link node (a anchor) we have to change the content of its property href. To do this first we have to access the specific code by the DOM method

document.getElementById('id')

After we assign the new URL as content in the current node href property referring in the access method the id name of the node and its property href as the JavaScript statement that follows.

document.getElementById('port').href = "http://www.w3opensource.com"

But the text which is embedded into the element node (a anchor) with id="port" is its child node (text type) and must change it with a new text content that will inform the user that is going to move in the new site through the new URL .

Here is the lesson to be learned. This can be done using the property innerText as we will see later.

5.5.1. The logic of the DOM script

For this reason we create a JavaScript function, with name changeLink() that is executed through the event handler onclick="changeLink()", when user clicks on the button of URL change and the event takes place.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Notice that the function basically executes two JavaScript statements which access the specific node and assign to its property the new content.

The element node anchor a inside the body of the HTML document is accessed by its id name (id="port"). Its content defines a child node (text node) of it with content "know about W3C.org", as the following structure..

know about W3C.org

In order to change the text node content "know about W3C.org" we could use the DOM method replaceChild(newText, oldText), or a direct access DOM method for the child node assigning a string content to it as the following code.

str = "know about w3opensource.com"; document.getElementById("port").childNodes [0].nodeValue = str;

But the new creativity sense of this program in the using of innerText attribute. This leads us to a more flexible DOM code as well as the innerText attribute is implemented on text nodes in order to change their content which must be always text.

Then our function will assign two values into the respective properties of the specific nodes as follows:

function changeLink() { document.getElementById('port').innerText= "know about w3opensource.com" document.getElementById ('port').href="http://www.w3opensource.com" }

5.5.2. The full coded HTML document with the DOM script

Inside the body of the HTML document we create a button with the related message about the URL change as the code that follows.

As you can see an onclick event handler was entered as a property into the

If you read the document above with IE 6.0 you will get following screens:

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Clicking on the link "know about the W3C.org IE will go to this specific URL and the home page of W3.org will display on your screen like the following screen:

If you push the button "Link (URL) change destination" to change the initial link to a new one, the function changeLink() will be executed and the new link with its description "know about w3opensource.com" will appear.

As you show in our document above when the function changeLink() is executed as value of the onClick event handler the specific node with id=port is accessed by the DOM method document.getElementById('port'). Thus, with two JavaScript statements we assign the new values to the specific attribute nodes "href" and "text".

Then you will see a screen like the following:

Finally, clicking on the new link you will go to the home page of w3opemsource.com which is

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

the screen that follows:

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

6. Summary

During this book you show how an HTML-XHTML or XML document when is reading from a browser that supports W3C-DOM is transformed to a DOM document with a tree or family structure.

You knew that DOM, as an application program interface (API), uses the nodes technology to describe the structure and the contents of a document and every HTML-XHTML or XML document element as well as its contents are represented by a certain DOM node.

You learned that the core object of the DOM structure is the Node.

Also, you learned that the whole point of DOM is modeling the document. so that every element can be used as an object, regardless of their structure in the document. As well as the nodes do not represent the organizational structure of the document, but its elements as objects with certain properties, values and methods referring to them.

You learned also all about nodes management and how you can create, insert, embed, replace or delete a node in the DOM document using the DOM methods and JavaScript.

You may have noticed that t the relationships among the nodes are defined by the organization and syntax of the HTML elements and the texts they may contain. Thus, each node can have no, one or more siblings which are nodes at the same level and share a common parent, as well as no, one or more children which are nodes contained in the specific node.

Finally you knew that DOM follows the same terminology as in JavaScript where objects containing other objects are called their parents and the contained objects are their children. So, DOM can refer to nodes containing other nodes, containing other nodes, etc.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

7. Teach your self at w3opensource.com

Browser Programming Technologies You can visit us for full description of each of the following Client Side Technologies to see their table of contents and the programming skills that you can get in order to complete your knowledge in Browser Programming.

z C110: Level: Basic An Introduction to HTML-XHTML and DOM

z C120: Level: Basic The complete guide of HTML-XHTML elements & tags

z C130: Level: Basic Style Sheets - Working with CSS

z C131: Level: Intermediate CSS Classes and Inheritance

z C140: Level: Intermediate DOM - Working with Document Object Model

z C150: Level: Basic An introduction to JavaScript Scripting Programming

z C151: Level: Basic The Structure of JavaScript

z C152: Level: Intermediate JavaScript Objects Development

z C153: Level: Intermediate JavaScript Advanced Features

z C154: Level: Advanced Dynamic Images and Image Maps with JavaScript

z C155: Level: Intermediate Cross Browser Scripting and Events Programming

z C160: Level: Advanced XML - The Basic Guide of (e)Xtensible Markup Language

z C165: Level: Advanced XSL - Transformations (XSLT)

NOTICE: The contents of this ebook as well as all ebooks that listed above are protected by Copyright Law: http://www.loc.gov/copyright/

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

8. Learn More

Document Object Model - Working with DOM

If you'd like to learn more about the structure and implementations of the W3C DOM in general, here's a list of specif web sites you might want to consider visiting:

z W3C -Document Object Model (DOM) http://www.w3.org/DOM/

z W3C - Recomendation of DOM Level 1 http://www.w3.org/TR/REC-DOM-Level-1

z W3C - Recomendation of DOM Level 2 http://www.w3.org/TR/REC-DOM-Level-2

z W3C - Recomendation of DOM Level 3 http://www.w3.org/TR/REC-DOM-Level-3

z From Wikipedia - Document Object Model (DOM) http://en.wikipedia.org/wiki/Document_Object_Model

z W3C -Document Object Model FAQ http://www.w3.org/DOM/faq.html

z W3C - Document Object Model (DOM) Level 3 XPath Specification http://www.w3.org/TR/2003/CR-DOM-Level-3-XPath-20030331/

z IBM - Discover key features of DOM Level 3 Core http://www-128.ibm.com/developerworks/xml/library/x-keydom.html

z W3C releases scripting standard, caveat http://news.com.com/2100-1023-979976.html

z IBM - Effective XML processing with DOM and XPath in Java http://www-128.ibm.com/developerworks/xml/library/x-domjava/

z W3C DOM Compatibility Tables http://www.quirksmode.org/dom/compatibility.html

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

9. Our e-Business Web Tutor Environment

Our development "Build your own eBusiness " model uses the web standard technologies for the Browser Programming (Client Side) and the open source software technologies for the Server Programming (Server Side) through Session Scripting Programming (SSP) methodology.

Through our eLearning Web model you can choose the right solution that will lead you with accuracy to your goals.

Web Tutor will show you the steps to build realistic and simple eBusiness applications. If you follow this approach through our "Build your own eBusiness " model you will save time and money.

We promote these values as well as the open source software that you are going to use is free and our know how and developing methodologies that will complete your Knowledge, will cost you through a symbolic price only of € 5.9 per ebook as well as w3opensource.com is a non profit education environment for web technologies.

Session Scripting Programming - SSP methodology,

is a web development methodology that the founder and main author of w3opensource.com, Alex Gklinos was presented for his M.Sc in E-Commerce at School of Mathematics, Computing and Information Systems at Kingston University of London U.K.

Our model is a proposal to web based application developers, who want to create database - driven sites and they try to find professional ways to avoid the Users stormy access which makes their database server response slow and the web server latency time weak.

Using SSP methodology you can transfer - through the session variables - all database driven schema on Client Side and the user's browser to be able to navigate your eBusiness site through these session variables.

With this approach, only the first time in which a Client-User enters to the database - driven site, our model will create the session variables with menus and drop-down lists for site navigation keeping them alive ( the session variables) in Web Server cache memory for as long as the user stays in the site.

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Copyright © by w3opensource.com

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein.

Although every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions. Neither is any liability for damages resulting from the use of the information contained herein.

Trademarks

All trademarks and service marks mentioned in this book are the property of their respective owners. w3opensource.com cannot attest to the accuracy of this information. When a term is used in this book should not be regarded as affecting the validity of any trademark or service mark.

Disclaimer

This book was written and published by the authors and w3opensource.com though the current scientific methodologies and as well as they have been set by the independent international organizations. Thus, this book has digitally signed by its author as complete and as accurate as possible, but no warranty or fitness is implied.

The information provided is on an "as is" basis. The authors and the the publisher- w3opensource.com shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the CD-ROM or programming code accompanying it.

Quantity Orders

We offer excellent discounts on this book when ordered in quantity for bulk purchases or special sales.

For more information, please contact

U.S. Corporate-Government and Universities Sales

[email protected]

Europe Corporate-Government and Universities Sales

[email protected]

For sales outside U.S.A and Europe please contact

International Sales

[email protected]

Copyright © w3opensource.com. All rights reserved. Document Object Model - Working with DOM Alex Gklinos M.Sc. in E-Commerce

Copyright © w3opensource.com. All rights reserved.