Meditation and Mindfulness for Software / IT Professionals. Conducted by Bipin Joshi in Thane. Read more...

W3C Document Object Model and HTML

Introduction

Dynamic HTML has brought great improvements to static web pages. However, the main problem with DHTML is cross-browser compatibility. Both the leading browsers IE and Netscape have different approach for DHTML and it makes script writer's life difficult.

With the introduction of Document Object Model(DOM) from W3C this problem is greatly solved. DOM presents a standard object model which is followed by IE 5+ and NS 6

Difference between DHTML ad W3C DOM

DHTML has its own properties and methods for each HTML tag and each tag can be accessed individually.

DOM presents a generic object model. DOM views at HTML document as a tree. It provides generic properties and methods which allow us to navigate and manipulate various 'Nodes'. Unlike DHTML, DOM lacks event handling and programmer has to take help of familiar DHTML events.

Most of the familiar DHTML objects like document, Forms and Images still exist in DOM.

Using the DOM, we can:

  • Create elements and attach them to any point in the document tree.
  • Manipulate tree branches in a document and insert the changed branches back into the tree.
  • Delete elements.
  • Move one part of the document tree to another without destroying and recreating the content.
  • Search the document for a string.
  • Search the tags for a given attribute.

Important Members of the Object model

The DOM exposes objects, collections, properties, and methods. Following table lists    a few of the most important methods, Properties and collections.

Document Methods
createElement(tagName)                
creates a new tag.
createTextNode(data)                
creates new content for the document.
createAttribute(name)                
creates an attribute for a tag.
getElementsByTagName(tagname)                 
returns a list of matching nodes (NodeList).
HTMLDocument Methods
An HTMLDocument object has these methods in addition to the methods of Document.
open()                
Opens a document for new content.
close()                 
Closes a document.
write(text)                
Appends the text to the open document.
writeln(text)               
Appends text and a new line to the open document.
getElementById(elementId)                 
returns the element with the given ID.
Element Methods
An Element has these methods in addition to the methods of Node.
getAttribute(name)               
Gets the value of the named attribute.
setAttribute(name, value)               
Sets the value of the named attribute.
removeAttribute(name)               
Removes the named attribute.
getElementsByTagName(name)               
Returns a list of matching nodes (NodeList).
Node Methods
insertBefore(newChild, refChild)               
Inserts a child node into the document before the given node.
replaceChild(newChild, oldChild)               
Replaces the old node with the new node.
removeChild(oldChild)               
Removes the child node from the document.
appendChild(newChild)               
Adds the node to the document.
hasChildNodes()               
Returns true if the node has children.
cloneNode(deep)               
Generates a copy of the tree under the given node.
Node Properties
firstChild	               
returns reference to first child node
lastChild               
returns reference to last child node
previousSibling               
returns reference to previous node which is at the same level as the current node
nextSibling               
returns reference to next node which is at the same level as the current node
parentNode               
returns reference to parent node
nodeName               
returns name of the node like TABLE
nodeType               
returns 1 for Tag,2 for attribute and 3 for text node
nodeValue               
returns/set text from a text node
data               
returns/set text from a text node
src	               
returns/sets image url for IMG element
Node Collections
childNodes               
returns list of child nodes of current node
attributes               
returns list of attributes of current node

Examples :

We will now see some examples of how to use DOM. For that we will use following simple HTML file

Note : Here, one peculiar thing to be noted is even though we omit TBODY element, one will be assumed by default by DOM

<html>
<head>
<title></title>
</head>

<body id=body1>
<table id=table1>
<tbody>
<tr><td>Data1</td><td>Data2</td></tr>
<tr><td>Data1</td><td>Data2</td></tr>
</tbody>
</table>

<form id=form1 name=form1>
<input id=btn1 name=btn1 type=button value=Click onclick="display();">
</form>

</body>
</html>

Example of Navigating a Table

Now, we will navigate through the table and display all the data contained in it.
Add the following in display() function in the head section.

function display()
{
alert("Table has " + table1.firstChild.childNodes.length+" rows");

for(i=0;i<table1.firstChild.childNodes.length;i++)
{
    alert(table1.firstChild.childNodes[i].childNodes[0].childNodes[0].nodeValue); //Data1
    alert(table1.firstChild.childNodes[i].childNodes[1].childNodes[0].nodeValue); //Data2
}

}

Example of Dynamically Changing Table Contents

Here, the code to access the individual cell content remains the same as above but we need to assign the value to the cells like :

table1.firstChild.childNodes[i].childNodes[0].childNodes[0].nodeValue="some value";

 

Example of Dynamically Adding/Removing Rows to Table

Now, let us add some new rows to the table

Add a new function AddRow() as follows :

function AddRows()
{
var row,col1,col2,txt1,txt2;

txt1=document.createTextNode("this is new text 1");
txt2=document.createTextNode("this is new text 2");

row=document.createElement("TR");

col1=document.createElement("TD");
col2=document.createElement("TD");

col1.appendChild(txt1);
col2.appendChild(txt2);

row.appendChild(col1);
row.appendChild(col2);

table1.firstChild.appendChild(row)

}

Here, we first created the content of the new cells using createTextNode method. Then we created a new TR element, two TD elements using createElement method. These elements yet do not belong to any specific table. We attach them to the table using appendChild method.

Now, we will remove rows from the table. This is done using removeChild method as follows:
table1.firstChild.removeChild(table1.firstChild.childNodes[0]);




Bipin Joshi is a software consultant, an author and a yoga mentor having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 18 Dec 2000



Tags : XML